【问题标题】:Typescript - Exclude enum values with functionTypescript - 使用函数排除枚举值
【发布时间】:2021-04-21 13:04:34
【问题描述】:

我正在尝试过滤掉枚举值,但在输入/过滤这些条目时遇到了一些问题。我无法正确输入过滤器功能。我花了几个小时,我不知道该怎么做。

我想要达到的目标:

我有这样的枚举:

enum AllEntries {
    A = 'a',
    B = 'b',
    C = 'c',
    D = 'd'
}

我想让这个枚举为数组中的某些键过滤掉一些条目:

const testObject = {
    // this one should have possibility to access all enum keys except A
    withoutA: filterEnum(AllEntries, [AllEntries.A]),

    // this one should have possibility to access all enum keys except A
    all: AllEntries,

    // this one should have possibility to access only D entry
    onlyD: filterEnum(AllEntries, [AllEntries.A, AllEntries.B, AllEntries.D])
}

我希望函数 filterEnum 返回 AllEntries 的“克隆”而不在第二个参数中给出值,它也不应该允许我访问例如。 testObject.withoutA 中的一个键

我正在尝试使用排除实用程序类型等,但没有结果。你有什么想法吗?

显示我想要实现的目标的示例代码(带有讨厌的any):

here

【问题讨论】:

    标签: javascript typescript enums


    【解决方案1】:

    首先,没有动态Enums

    最好使用不可变对象而不是枚举,因为数值存在问题。

    const All = {
      A: 'a',
      B: 'b',
      C: 'c'
    } as const;
    
    type All = typeof All;
    
    const remove = <T, P extends keyof T>(obj: T, prop: P) => {
      const { [prop]: _, ...rest } = obj;
      return rest
    }
    
    const filterOut = <T extends keyof All>(obj: All, exclude: T[]): Omit<All, T> =>
      exclude.reduce(remove, obj as any)
    
    
    const withoutA = filterOut(All, ['A']); // ok
    const onlyC = filterOut(All, ['A', 'B']) // ok
    

    如果没有类型转换(as 运算符),在 TS 中很难生成 reduce

    Playground

    【讨论】:

      猜你喜欢
      • 2019-05-19
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      相关资源
      最近更新 更多