首页 > 解决方案 > How to force interface key of certain enum type?

问题描述

Considering this interface:

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

And these enums:

export enum EuropeanCars {
  MAKE_A = 1
  MAKE_B = 2
}

export enum AmericanCars {
  MAKE_A = 3
  MAKE_B = 4
}

I want to build objects and force them to have the keys of the enum type:

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

Currently, I'm getting this error in the interface: key:E --- An index signature parameter type must be either 'string' or 'number'.

标签: typescriptenumsinterfacetypescript2.0

解决方案


您可以使用映射类型而不是接口:

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' },
}

操场


推荐阅读