Typescript Unions 接口和原语
Typescript Unions interface and primitive
考虑这个例子
interface fooInterface {
bar: any;
}
function(value: fooInterface | string) {
value.bar
}
错误是:属性 'bar' 在类型“(fooInterface | string)”上不存在
我显然做错了什么。我想说的基本上是:值是实现 fooInterface 的对象或字符串。
我该怎么做?
谢谢
您不能使用 value.bar
,因为它绝对 不安全。它可能是安全的(因为 value 可能是一个字符串),但编译器不确定,并且它不会让你做 .bar
除非它确定。您可能想要做的是使用 type guard:
if (typeof value !== "string") {
value.bar
// This compiles happily, because inside this if, value has
// type 'fooInterface'. That's because TS now knows it isn't a string,
// so *must* be a fooInterface.
}
你可以玩这个 in the typescript playground:注意只有一个 value.bar
失败了,因为它知道只有那个是错误的。
如果你不能t/don不想这样做,你可以只告诉编译器你知道你在用类型断言做什么(例如 var definitelyFoo = <fooInterface> value
),但是守卫通常是更好的选择。
如果您告诉 value
是 fooInterface
或 string
类型,您必须在使用 value
之前检查类型。在您的情况下,您只需使用 typeof
检查 value
是否为 string
。如果不是,那就是fooInterface
.
interface fooInterface {
bar: any;
}
function(value: fooInterface | string) {
if (typeof value === "string") {
// The compiler now knows that value is string
}
else {
/* The compiler is smart and knows that the value
must be of type fooInterface. */
value.bar
}
}
在其他情况下,您必须使用 instanceof
(for checking whether object is typeof specific class) or your own type checks(如果有多个接口或自定义类型)。
考虑这个例子
interface fooInterface {
bar: any;
}
function(value: fooInterface | string) {
value.bar
}
错误是:属性 'bar' 在类型“(fooInterface | string)”上不存在
我显然做错了什么。我想说的基本上是:值是实现 fooInterface 的对象或字符串。
我该怎么做?
谢谢
您不能使用 value.bar
,因为它绝对 不安全。它可能是安全的(因为 value 可能是一个字符串),但编译器不确定,并且它不会让你做 .bar
除非它确定。您可能想要做的是使用 type guard:
if (typeof value !== "string") {
value.bar
// This compiles happily, because inside this if, value has
// type 'fooInterface'. That's because TS now knows it isn't a string,
// so *must* be a fooInterface.
}
你可以玩这个 in the typescript playground:注意只有一个 value.bar
失败了,因为它知道只有那个是错误的。
如果你不能t/don不想这样做,你可以只告诉编译器你知道你在用类型断言做什么(例如 var definitelyFoo = <fooInterface> value
),但是守卫通常是更好的选择。
如果您告诉 value
是 fooInterface
或 string
类型,您必须在使用 value
之前检查类型。在您的情况下,您只需使用 typeof
检查 value
是否为 string
。如果不是,那就是fooInterface
.
interface fooInterface {
bar: any;
}
function(value: fooInterface | string) {
if (typeof value === "string") {
// The compiler now knows that value is string
}
else {
/* The compiler is smart and knows that the value
must be of type fooInterface. */
value.bar
}
}
在其他情况下,您必须使用 instanceof
(for checking whether object is typeof specific class) or your own type checks(如果有多个接口或自定义类型)。