【问题标题】:Typescript implement interface with same keys but different typesTypescript 实现具有相同键但类型不同的接口
【发布时间】:2022-01-27 00:11:50
【问题描述】:

我有一个界面

export interface Foo {
 a: string;
 b: string;
}

我现在想要另一个类,它实现了接口的所有键,但可以有另一种类型:

  export class Bar implements keysof(Foo) {
    a: SomeNewType;
    b: SomeNewType2;
  }

这在打字稿中可能吗? 背景:我希望Bar 类的键与Foo 同步

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以使用键映射来执行此操作。

    export interface Foo {
      a: string;
      b: string;
    }
    
    type HasKeys<T> = {
      [P in keyof T]: any;
    }
    
    export class Bar implements HasKeys<Foo> {
    
    }
    

    这会抱怨Bar 缺少ab,但是如果你用任何类型定义它们就可以了。即

    export class Bar implements HasKeys<Foo> {
      a: number;
      b: object;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-28
      • 2020-06-25
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多