鉴于以下设计的代码示例,其中T
可能是Function
,也可能不是class Test<T> {
constructor(public value: T) {}
method() {
if (this.value instanceof Function) {
let fn = <Function>this.value; // [ts] Neither type 'T' nor type 'Function' is assignable to the other.
fn();
}
}
}
let test = new Test(() => {});
test.method();
,如何以允许我执行它的方式将其转换为Typescript(假设这是可能的)在所有)?
let fn: (input: T) => any = <(input: T) => Test<T>>this.value;
如果这是可以解决的,我是否可以将其转换为特定的函数签名,如下所示?
[TestClass]
public class JsonToXmlTests : MiscUnitTests {
[TestMethod]
public void Xml_Should_Convert_To_JSON_And_Object() {
string xml = "<POSLog MajorVersion=\"6\" MinorVersion=\"0\" FixVersion=\"0\"><Cash Amount = \"100\"></Cash></POSLog>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.None, true);
//Attributes are prefixed with an @ and should be at the start of the object.
jsonText = jsonText.Replace("\"@", "\"");
POSLog actual = JsonConvert.DeserializeObject<POSLog>(jsonText);
actual.Should().NotBeNull();
actual.MajorVersion.Should().Be("6");
actual.MinorVersion.Should().Be("0");
actual.FixVersion.Should().Be("0");
actual.Cash.Should().NotBeNull();
actual.Cash.Amount.Should().Be("100");
}
public class Cash {
public string Amount { get; set; }
}
public class POSLog {
public string MajorVersion { get; set; }
public string MinorVersion { get; set; }
public string FixVersion { get; set; }
public Cash Cash { get; set; }
}
}
我有一个半合法的用例(可以添加背景,如果有必要的话),但我不知道我是否想知道我是否通过一个圆孔敲击方形钉。
答案 0 :(得分:1)
类型'T'和类型'Function'都不能分配给另一个。
您可以使用双重断言强制它:
let fn = this.value as any as Function;
此处介绍:https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html
我可以在功能界面
中使用双断言吗?
当然:
let value: number;
let fn = this.value as any as (input:string)=>any;