【问题标题】:Using generic type with class - type T does not satisfy the constraint使用具有类的泛型类型 - 类型 T 不满足约束
【发布时间】:2019-02-10 00:12:15
【问题描述】:
export type OptionsToType<T extends Array<{ name: Array<string>, type: keyof TypeMapping }>>
  = { [K in T[number]['name'][0]]: TypeMapping[Extract<T[number], { name: K }>['type']] }


export class CliParser<T> {

  opts: OptionsToType<T>;

  constructor() {

  }

}

我收到此错误:

有谁知道如何解决这个问题?

【问题讨论】:

    标签: typescript tsc typescript3.0


    【解决方案1】:

    由于T 可以是CliParser 上的任何类型,因此对于OptionsToType 来说太宽泛了。您可以通过以下方式限制它:

    export class CliParser<T extends Array<{ name: Array<string>, type: keyof TypeMapping }>> {
    
      opts: OptionsToType<T>;
    
      constructor() {
    
      }
    
    }
    

    确实有点丑。您可能希望将 Array&lt;{ name: Array&lt;string&gt;, type: keyof TypeMapping }&gt; 设为自己的类型。

    【讨论】:

      猜你喜欢
      • 2017-01-21
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      • 2018-03-05
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多