考虑这个例子。
interface fooInterface {
bar: any;
}
function(value: fooInterface | string) {
value.bar
}
错误信息为:“在类型 '(fooInterface | string)' 上不存在属性 'bar'”
显然,我做错了什么。我的意思是:value 可以是实现 fooInterface 接口的对象或者是一个字符串。
我该怎么做呢?
谢谢。
bar
属性,所以像那样访问它是错误的。你实际上想做什么? - artem(<fooInterface>value).bar
或(value as fooInterface).bar
来让TypeScript相信你的真实性。 - Misaz