Extend interface to contain a date type

China☆狼群 提交于 2021-02-05 09:43:50

问题


I need to extend an interface in Typescript to contain a Date type.

I have tried the following

interface WithDate {
  [key: string]: Date;
}

But when I try to extend WithDate, I get the error:

interface Person extends  WithDate {
  id: number; // Property 'id' of type 'number' is not assignable to string index type 'Date'
  name: string;
  date: Date;
}

Any ideas how to fix this error? Many thanks


回答1:


interface WithDate {
  [key: string]: Date;
}

With this interface you are telling TypeScript that objects implementing this interface can have string keys but only 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
}

So when you extend the WithDate interface, TypeScript sees the index signature and attempts to merge these interfaces, however, there are conflicting shapes here:

{ id: string }

and

{ [k: string]: Date }

So the compiler tries its best to solve these conflicts and because this is a fairly ambiguous situation, TypeScript has to choose some a shape and it chooses { [k: string]: Date } because this is the most expected/correct behaviour for interface extensions.

You probably intended to do this:

interface WithDate {
 date: Date
}

interface Person extends WithDate {
 id: number;
 name: string;
}

const person: Person = {
 id: 1,
 date: new Date(),
 name: 'bob'
}




回答2:


Name the field in WithDate:

interface WithDate {
  date: Date; // Note field name : date
}
interface Person extends  WithDate {
  id: number;
  name: string;
}


来源:https://stackoverflow.com/questions/63071377/extend-interface-to-contain-a-date-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!