【问题标题】:Specific types that inherit from more abstract types从更抽象类型继承的特定类型
【发布时间】:2021-01-23 16:29:56
【问题描述】:

我是 Typescript 的新手,如果这很明显,我深表歉意。 我有一个类和一个与之关联的类型,如下所示。


    interface childType {
      a: string;
      b: string;
    }

    class Child extends Parent {
      instanceVar: childType
    }

这个类从一个父类扩展而来。 在父级中,instanceVar 是类型 Record。 有一个名为 getValues 的函数枚举该 Record 并返回一个字符串数组


    class Parent {
      instanceVar: Record<string, string>
    
      constructor(iV: Record<string, string>) {
        this.instanceVar = iV; 
      }

      getAllValues = (): Array<string> =>{
        let values : Array<string> = [];
        Object.keys(this.instanceVar).forEach((key) => {
          let val = this.instanceVar[key];
          values.push(val);
        })
        return values;
      }
    
    }

这目前不起作用,打字稿抱怨 Child 中的 instanceVar 与 parent 类型不同。然而对我来说,这是因为“childType”基本上是一个记录(字符串映射到字符串),但更“具体”。

我知道我可以使用泛型解决类型错误,但我的真正目标是不必重写子类中的 getValues 函数。我想在父类中编写一次 getValues,并将其应用于所有子类。这意味着子类中的 instanceVar 以某种方式从 Record 类型“继承”其类型。

【问题讨论】:

    标签: typescript dictionary generics inheritance key-value


    【解决方案1】:

    您可以将其作为父级的通用参数,而不是在子级中重新定义instanceVar。这还需要对 Object.keys 的值进行类型断言,因为默认情况下,Typescript 的类型比你想要的更广泛,但这是相当标准的。试试:

    class Parent<T extends Record<keyof T, string>> {
      instanceVar: T
    
      constructor(iV: T) {
        this.instanceVar = iV; 
      }
    
      getAllValues = (): Array<string> =>{
        let values : Array<string> = [];
        const keys = Object.keys(this.instanceVar) as (keyof T)[] // <-- type assertion
        keys.forEach((key) => {
          let val = this.instanceVar[key];
          values.push(val);
        })
        return values;
      }
    
    }
    
    interface childType {
      a: string;
      b: string;
    }
    
    class Child extends Parent<childType> {
    
    }
    

    【讨论】:

    • 什么是“模板参数”?这是 C++ 术语吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2017-04-24
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    相关资源
    最近更新 更多