【发布时间】:2021-06-21 12:57:29
【问题描述】:
我很好奇枚举与 keyof 关键字的用法。
这是没有枚举的示例代码。
const map = new Map<string, string>();
interface ShopStoreProps {
google: string;
apple: string,
galaxy: string
}
const setValue = <T extends keyof ShopStoreProps>(shopProps: T, value: string) => {
return map.set(shopProps, value);
}
setValue('google', 'test1'); // ok
setValue('appleee', 'test2'); // error
但我只想使用枚举而不是这样的上层接口。
当然我知道下面的setValue function在语法上是错误的。
感谢您阅读这个问题。 :)
const map = new Map<string, string>();
enum ShopStoreEnum {
GOOGLE = 'google',
APPLE = 'apple',
GALAXY = 'galaxy',
}
const setValue = <T extends keyof ShopStoreEnum>(shopProps: T, value: string) => {
return map.set(shopProps.name, value);
}
setValue(ShopStoreEnum.GOOGLE, 'test1'); // to be
【问题讨论】:
-
setValue是否必须是shopProps类型的泛型?
标签: typescript enums