我有两个对象,一个有属性数据,另一个没有:
const jsonWithNoData = {}
const jsonWithData = { data: [1, 2, 3] }
采取联合后,我尝试执行类型缩小:
const jsonWithNoData = {}
const jsonWithData = { data: [1, 2, 3] }
type JsonWithNoData = typeof jsonWithNoData
type JsonWithData = typeof jsonWithData
type JsonData = JsonWithNoData | JsonWithData // <--- union here
function foo(arg:JsonData) {
if (arg && arg.data) {
// ^^^^<-------[tsserver 2339] Property 'data' does not exist on type 'JsonData'.
return arg.data
// ^^^^<---------[tsserver 2339] Property 'data' does not exist on type 'JsonData'.
} else {
return 'no data'
}
}
console.log(foo({}))
我收到一条错误消息:[tsserver 2339] 类型“JsonData”上不存在属性“数据”
但为什么? union 不是意味着 jsonWithNoData OR jsonWithData 吗?如果是这样,为什么我的类型保护不合法?
上面的片段可以找到
Update:
为了真正说明打字稿cannot查看属性“data”,这不是因为我的类型保护逻辑中的错误,我将上面的内容重写如下:
const jsonWithNoData = {}
const jsonWithData = { data: [1, 2, 3] }
type JsonWithNoData = typeof jsonWithNoData
type JsonWithData = typeof jsonWithData
type JsonData = JsonWithNoData | JsonWithData // <--- union here
function foo(arg:JsonData) {
const isObject = arg && (Object.prototype.toString.call(arg) === '[object Object]')
if ( isObject && Object.prototype.hasOwnProperty.call(arg, 'data') ) {
// now we are sure that the property 'data' does exist !!
return arg.data
// ^^^^<----But we still get error
// [tsserver 2339] Property 'data' does not exist on type 'JsonData'.
} else {
return 'no data'
}
}
console.log(foo({ data: [1, 2, 3] }));
您可以看到类型错误仍然存在。
你可以找到更新片段: