扩展接口以包含日期类型 [英] Extend interface to contain a date type

查看:56
本文介绍了扩展接口以包含日期类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Typescript中扩展一个接口以包含Date类型.

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

我尝试了以下

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

但是当我尝试扩展 WithDate 时,出现错误:

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

推荐答案

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

使用此接口,您正在告诉TypeScript实现该接口的对象可以具有 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
}

因此,当您扩展 WithDate 接口时,TypeScript会看到索引签名并尝试合并这些接口,但是,这里存在冲突的形状:

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:字符串}

{[k:字符串]:日期}

因此,编译器会尽力解决这些冲突,并且由于这是一个相当模糊的情况,因此TypeScript必须选择某种形状,然后选择 {[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.

您可能打算这样做:

interface WithDate {
 date: Date
}

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

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

这篇关于扩展接口以包含日期类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆