Typescript 1.8引入了字符串文字类型.但是,当作为参数传入对象时,如下所示:
const test = { a: "hi",b: "hi",c: "hi" }; interface ITest { a: "hi" | "bye" } function testFunc (t: ITest) { } testFunc(test);
它失败了:
Argument of type ‘{ a: string; b: string; c: string; }’ is not assignable to parameter of type ‘ITest’.
Types of property ‘a’ are incompatible.
Type ‘string’ is not assignable to type ‘”hi” | “bye”‘.
Type ‘string’ is not assignable to type ‘”bye”‘.
我希望这可以工作,因为它符合接口的要求,但我可能会忽略某些东西.
解决方法
test.a的类型已被推断为字符串而不是“hi”.编译器正在比较类型而不是初始字符串表达式.
为了使这项工作,您需要键入该属性为“hi”| “再见”:
type HiBye = "hi" | "bye"; const test = { a: "hi" as HiBye,c: "hi" }; interface ITest { a: HiBye } function testFunc (t: ITest) { } testFunc(test);
请注意,在原始情况下,编译器将test.a的类型推定为“hi”是没有意义的,因为在到达testFunc(test)-ex之前可以为test.a指定一个不同的值. test.a =“不喜”.
旁注:编译器不会推断类型为偶数字符串变量的字符串表达式.这也会导致很多烦恼…想象一下:
const myVariableTypedAsHi = "hi"; // implicitly typed as "hi" let otherVar = myVariableTypedAsHi; // otherVar implicitly typed as "hi" otherVar = "test"; // error: cannot assign `"test"` to `"hi"`—well that would be annoying