![](/img/trans.png)
[英]How can I specify loosely typed object literal in typescript definition?
[英]Typescript string literal with duck-typed object
Typescript 1.8引入了字符串文字类型。 但是,将对象作为参数传递时,如下所示:
const test = {
a: "hi",
b: "hi",
c: "hi"
};
interface ITest {
a: "hi" | "bye"
}
function testFunc (t: ITest) {
}
testFunc(test);
它失败了:
类型'{a:string; b:字符串; c:字符串; }'不能分配给'ITest'类型的参数。 属性'a'的类型是不兼容的。 类型'string'不能分配给''hi“|类型 “再见”。” 类型'string'不能分配给'“bye”'。
我希望这可以工作,因为它符合界面的要求,但我可能会忽略一些东西。
test.a
的类型已被推断为string
而不是"hi"
。 编译器正在比较类型而不是初始字符串表达式。
为了完成这项工作,您需要将该属性键入"hi" | "bye"
"hi" | "bye"
:
type HiBye = "hi" | "bye";
const test = {
a: "hi" as HiBye,
b: "hi",
c: "hi"
};
interface ITest {
a: HiBye
}
function testFunc (t: ITest) {
}
testFunc(test);
请注意,在原始情况下,编译器将test.a
的类型推断为"hi"
是没有意义的,因为您可以在test.a
到testFunc(test)
-ex之前为test.a
分配不同的值。 test.a = "not hi"
。
旁注:编译器不会推断类型是偶数常量字符串变量的字符串表达式。 这也会导致很多烦恼......想象一下:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.