Typescript - 联合类型

2024-05-12

我创建了以下界面:

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'.

为什么编译器会搜索seconds in Date并且不适用于Timestamp type?


简答

为什么编译器在 Date 中搜索秒而不使用 Timestamp 类型?

使用联合类型时,编译器仅允许访问属性存在于所有类型上。你的错误发生是因为seconds仅存在于Timestamp并且也不在Date.

Example

这里我们创建一个Message有一个Timestamp为其date.

const message: Message = {
  date: {
    seconds: 10, 
    nanoseconds: 10
  }
}

在下面的代码中,编译器不知道date is a Timestamp。就编译器而言,date是一个Date or a 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;
}

有关的文档类型守卫在这里 https://www.typescriptlang.org/docs/handbook/advanced-types.html.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Typescript - 联合类型 的相关文章

随机推荐