我需要扩展 Typescript 中的接口以包含日期类型。
我尝试过以下方法
interface WithDate {
[key: string]: Date;
}
但当我尝试延长WithDate
,我收到错误:
interface Person extends WithDate {
id: number; // Property 'id' of type 'number' is not assignable to string index type 'Date'
name: string;
date: Date;
}
有什么想法如何修复这个错误吗?非常感谢
interface WithDate {
[key: string]: Date;
}
通过此接口,您可以告诉 TypeScript 实现此接口的对象可以具有string
键但仅Date
values.
const obj: IWithDate = {
key1: new Date(), // OK because it's a date
key2: new Date('2020-01-01') // OK, another date
key3: '2020-01-01' // Error, not a Date
key4: true // Error, not a Date
key5: 123 // Error, not a Date
// and any other objects besides `Date`s will cause a compiler error
}
所以当你extend
the WithDate
接口,TypeScript 看到索引签名并尝试合并这些接口,但是,这里存在冲突的形状:
{ id: string }
and
{ [k: string]: Date }
因此编译器会尽力解决这些冲突,并且由于这是一个相当模糊的情况,TypeScript 必须选择一些形状,它会选择{ [k: string]: Date }
因为这是接口扩展最期望/最正确的行为。
您可能打算这样做:
interface WithDate {
date: Date
}
interface Person extends WithDate {
id: number;
name: string;
}
const person: Person = {
id: 1,
date: new Date(),
name: 'bob'
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)