我创建了以下界面:
export interface Message{
date: Timestamp | Date;
}
interface Timestamp {
seconds: number;
nanoseconds: number;
}
不知道为什么 - 我收到以下错误:
Property 'seconds' does not exist on type 'Date | Timestamp'.
Property 'seconds' does not exist on type 'Date'.
为什么编译器在 Date
中搜索 seconds
而不适用于 Timestamp
类型?
最佳答案
简短回答
Why does the compiler searches for seconds in Date and doesn't work with the Timestamp type?
使用联合类型时,编译器仅允许访问所有类型上存在的属性。发生错误是因为 seconds
仅存在于 Timestamp
上,而不存在于 Date
上。
示例
这里我们创建一个消息
,其日期
有一个时间戳
。
const message: Message = {
date: {
seconds: 10,
nanoseconds: 10
}
}
在下面的代码中,编译器不知道date
是Timestamp
。就编译器而言,date
可以是 Date
或 Timestamp
。
// Property 'seconds' does not exist on type 'Timestamp | Date'.
// Property 'seconds' does not exist on type 'Date'.
const seconds = message.date.seconds;
类型保护
为了向编译器提供更多信息,我们可以添加类型保护。然后编译器就会知道,在 if
语句中,它正在处理 Timestamp
。
if (!(message.date instanceof Date)) {
// now we know we are dealing with a Timestamp
// the compiler will not output an error
const seconds = message.date.seconds;
}
关于 type guards is here 的文档.
关于Typescript - 联合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53563935/