【问题标题】:how to define generic interface based on class generic如何基于类泛型定义泛型接口
【发布时间】:2020-03-22 17:12:58
【问题描述】:

我正在尝试基于另一个接口创建一个新的增强型通用接口。基本接口定义了对象将具有的属性 (root)。增强类型应该具有相同的属性,但不是any 作为值,而是得到一个更复杂的对象。请注意,接口IStyleObj 在泛型类中使用,其中泛型类型被传递给泛型接口。

在我的实验中,我遇到了这些错误,但我不知道如何修复它们:

"IStyleObj<T>"
'T' is declared but its value is never read.ts(6133)

"Key in keyof"
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
Member '[K in keyof' implicitly has an 'any' type.ts(7008)

"... T"
Cannot find name 'T'.ts(2304)

"class: any"
'any' only refers to a type, but is being used as a value here.ts(2693)

这是我当前的代码:

// Child.ts
interface IStyles {
  root?: any
}

// Base.ts
interface IStyleObj<T> {
  [K in keyof T]: {
    class: any
    style: any
  }
}

export default class Base<IStyles = {}> {
  get styles (): IStyleObj<IStyles> {
    // ...
  }
}

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    接口不能映射类型,只有类型别名可以。这将起作用:

    // Child.ts
    interface IStyles {
      root?: any
    }
    
    // Base.ts
    type IStyleObj<T> = {
      [K in keyof T]: {
        class: any
        style: any
      }
    }
    
    export default class Base<IStyles = {}> {
      get styles (): IStyleObj<IStyles> {
        return null!
      }
    }
    

    Playground Link

    【讨论】:

      猜你喜欢
      • 2019-07-21
      • 2021-03-26
      • 2015-01-18
      • 1970-01-01
      • 2019-12-28
      • 2014-10-06
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多