【问题标题】:how to use typescript keyof in function arguments with enum values?如何在具有枚举值的函数参数中使用 typescript keyof?
【发布时间】: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


【解决方案1】:

只需使用extends,而不是extends keyof

const setValue = <T extends ShopStoreEnum>(shopProps: T, value: string) => {
    return map.set(shopProps, value);
}

有人可能会问,为什么要让它通用呢?你会得到同样的结果:

const setValue = (shopProps: ShopStoreEnum, value: string) => {
    return map.set(shopProps, value);
}

【讨论】:

  • 我想我觉得这太难了。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-19
  • 1970-01-01
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多