Typescript - 联合类型

标签 typescript union-types

我创建了以下界面:

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
  }
}

在下面的代码中,编译器不知道dateTimestamp。就编译器而言,date 可以是 DateTimestamp

// 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/

相关文章:

typescript - 为什么不能从子类调用抽象保护方法?

TypeScript 访问字典类型对象

css - 跨元素共享 css 和 ts

reactjs - React props - 努力区分联合类型

typescript - 如何在 TypeScript 中定义一个类型,它可以具有除特定属性之外的任何属性?

javascript - Vue 子 Prop 不会在父项中的绑定(bind)值更改时更新

c - 关于 C 中的 union

python - mypy Error TypeVar with Value Restriction and Union of Unions/Optional 无法传递通用容器类型

typescript - 如何映射联合数组类型?