Search code examples
typescripttsctypescript3.0

Using generic type with class - type T does not satisfy the constraint


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() {

  }

}

I get this error:

enter image description here

Does anyone know how to fix this one?


Solution

  • Since T can be any type on CliParser, it is too broad for OptionsToType. You can limit it by doing:

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

    Definitely a little ugly. You may want to make Array<{ name: Array<string>, type: keyof TypeMapping }> its own type.