typescript - 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'.
解决方案
您可以使用映射类型而不是接口:
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' },
}
推荐阅读
- hyperlink - 在 LaTeX 中超链接到 bibitem
- c - 优化 Cython:5 字节字符串还是 size_t?
- android - 在 Windows 中安装 APK 时将 Android 模拟器放在前面
- jquery - 根据枚举显示 selectOneMenu 项目背景颜色
- javascript - 获取某些json值并显示在html页面上
- processing - 处理,当我在代码顶部写一个类时,声音文件不可用
- node.js - 函数返回未定义、预期的 Promise 或值 - NodeJS
- node.js - 为什么在 app.use(express.static(path.join(...))); 前面没有触发 Express Middleware
- c - 不完整的类型与大小
- rust - rust中的元组和数组有什么区别?