如何强制某些枚举类型的接口键?

问题描述 投票:0回答:1

考虑此界面:

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个回答
0
投票

您可以使用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

© www.soinside.com 2019 - 2024. All rights reserved.