Typescript - union types

10 浏览
0 Comments

Typescript - union types

我创建了以下接口:

export interface Message{
  date: Timestamp | Date;
}
interface Timestamp {
  seconds: number;
  nanoseconds: number;
}

不知道为什么 - 我收到以下错误信息:

在类型'Date | Timestamp'上不存在属性'seconds'。
  在类型'Date'上不存在属性'seconds'。

为什么编译器在Date中搜索seconds,而不与Timestamp类型一起工作?

0
0 Comments

Typescript - union types问题的出现原因是,当使用联合类型时,编译器只允许访问所有类型上存在的属性。因此,当我们尝试访问一个只存在于其中一个类型上的属性时,会出现错误。

解决方法是添加一个类型保护(type guard),以便告诉编译器在特定条件下正在处理的是哪种类型。通过添加类型保护,编译器将知道在if语句块中处理的是Timestamp类型,从而避免报错。

下面是一个示例,我们创建了一个包含Timestamp类型的date属性的Message对象。

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)) { 
    // 现在我们知道正在处理的是Timestamp类型
    // 编译器将不会输出错误
    const seconds = message.date.seconds;
}

有关类型保护的详细文档可以在这里找到。

0