首页 > 解决方案 > 接口中的联合类型:“日期”类型上不存在属性“_seconds”

问题描述

我有两个接口:

interface Timestamp {
  _seconds: number;
  _nanoseconds: number;
}

interface Item {
  createdAt: Timestamp | Date;
}

但是编译后出现错误:

Property '_seconds' does not exist on type 'Timestamp | Date'.

我做错了什么?

标签: typescript

解决方案


您正在尝试访问_secondson item.createdAt,但是由于这是一个Union 类型,TS 不知道它的值在运行时是 aTimestamp还是 a Date,所以它警告您,如果它是 a Date_seconds它将是未定义的。

您可以使用in运算符来检查属性是否存在,在这种情况下,TS 会将createdAt类型缩小为Timestamp,现在您可以_seconds从编译器访问而不会出现错误:

if ('_seconds' in item!.createdAt) {
    item!.createdAt._seconds;
}

游乐场链接


推荐阅读