【问题标题】:How to force interface key of certain enum type?如何强制某些枚举类型的接口键?
【发布时间】:2020-08-31 01:02:13
【问题描述】:

考虑到这个接口:

export interface Vehicle<E> {
 [key: E]: {
   title: string
 }
}

还有这些枚举:

export enum EuropeanCars {
  MAKE_A = 1
  MAKE_B = 2
}

export enum AmericanCars {
  MAKE_A = 3
  MAKE_B = 4
}

我想构建对象并强制它们拥有枚举类型的键:

export const AmericanCarDetails: Vehicle<EuropeanCars> = {
...
}

目前,我在界面中收到此错误:key:E --- An index signature parameter type must be either 'string' or 'number'.

【问题讨论】:

    标签: typescript enums interface typescript2.0


    【解决方案1】:

    你可以用mapped type代替接口:

    export type Vehicle<E extends PropertyKey> = {
        [key in E]: {
            title: string
        }
    }
    
    export enum EuropeanCars {
        MAKE_A = 1,
        MAKE_B = 2
    }
    
    export enum AmericanCars {
        MAKE_A = 3,
        MAKE_B = 4
    }
    
    export const AmericanCarDetails: Vehicle<AmericanCars> = {
        [AmericanCars.MAKE_A]: { title: 'foo' },
        [AmericanCars.MAKE_B]: { title: 'foo' },
    }
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多