typescript - 接口中的联合类型:“日期”类型上不存在属性“_seconds”
问题描述
我有两个接口:
interface Timestamp {
_seconds: number;
_nanoseconds: number;
}
interface Item {
createdAt: Timestamp | Date;
}
但是编译后出现错误:
Property '_seconds' does not exist on type 'Timestamp | Date'.
我做错了什么?
解决方案
您正在尝试访问_seconds
on item.createdAt
,但是由于这是一个Union 类型,TS 不知道它的值在运行时是 aTimestamp
还是 a Date
,所以它警告您,如果它是 a Date
,_seconds
它将是未定义的。
您可以使用in
运算符来检查属性是否存在,在这种情况下,TS 会将createdAt
类型缩小为Timestamp
,现在您可以_seconds
从编译器访问而不会出现错误:
if ('_seconds' in item!.createdAt) {
item!.createdAt._seconds;
}
推荐阅读
- xml - 基于类似的子标签将 XML 节点聚集在一起。棒状节点还应该包含不相似的子标签
- python-3.x - Django:为过时的应用程序/模型清理 SQLite d/b
- python - 尝试使用 BayesSearchCV 调整 MLPClassifier hidden_layer_sizes 时出错
- mysql - 从mysql数据库中的多个表中选择数据
- javascript - 我怎样才能让innerHtml 只写一次错误?
- sql - 查询以从 select 语句中检索自定义列
- javascript - 纯 Javascript - 将数组转换为 csv 格式
- typescript - Firestore & Cloud Function:使用我自己的文档 ID 创建新的集合文档
- java - 如何从 url 获取参数值作为字符串
- ssl - Nginx 错误 https 。curl:(35)错误:1408F10B:SSL例程:ssl3_get_record:错误的版本号