[英]Typescript string literal with duck-typed object
Typescript 1.8 introduced the string literal type. Typescript 1.8引入了字符串文字类型。 However, when passing in an object as a parameter as in the following:
但是,将对象作为参数传递时,如下所示:
const test = {
a: "hi",
b: "hi",
c: "hi"
};
interface ITest {
a: "hi" | "bye"
}
function testFunc (t: ITest) {
}
testFunc(test);
It fails with: 它失败了:
Argument of type '{ a: string;
类型'{a:string; b: string;
b:字符串; c: string;
c:字符串; }' is not assignable to parameter of type 'ITest'.
}'不能分配给'ITest'类型的参数。 Types of property 'a' are incompatible.
属性'a'的类型是不兼容的。 Type 'string' is not assignable to type '"hi" |
类型'string'不能分配给''hi“|类型 "bye"'.
“再见”。” Type 'string' is not assignable to type '"bye"'.
类型'string'不能分配给'“bye”'。
I would expect this to work since it meets the requirements of the interface, but I might be overlooking something. 我希望这可以工作,因为它符合界面的要求,但我可能会忽略一些东西。
The type of test.a
has been inferred as string
and not "hi"
. test.a
的类型已被推断为string
而不是"hi"
。 The compiler is comparing the types and not the initial string expression. 编译器正在比较类型而不是初始字符串表达式。
In order to make this work you need to type that property as "hi" | "bye"
为了完成这项工作,您需要将该属性键入
"hi" | "bye"
"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);
Note that in the original case it wouldn't make sense for the compiler to infer the type of test.a
to be "hi"
because you can assign a different value to test.a
before it reaches testFunc(test)
—ex. 请注意,在原始情况下,编译器将
test.a
的类型推断为"hi"
是没有意义的,因为您可以在test.a
到testFunc(test)
-ex之前为test.a
分配不同的值。 test.a = "not hi"
. test.a = "not hi"
。
Side note: It's good the compiler doesn't infer the type the be the string expression for even constant string variables. 旁注:编译器不会推断类型是偶数常量字符串变量的字符串表达式。 That would also lead to a lot of annoyances... imagine this:
这也会导致很多烦恼......想象一下:
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.