0

I'm trying to filter out enum values and I have some issues with typings/filtering these entries. I cannot type my filter function correctly. I spent some hours and I have no idea how to do it.

What I want to achieve:

I have enum like:

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

And I want to have this enum to have some entries filtered out for some keys in array:

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])
}

I want function filterEnum to return "clone" of AllEntries without values given in second parameter, also it shouldn't allow me to access eg. A key in testObject.withoutA

I'm trying to use Exclude utility type etc, but with no results. Do you have any ideas?

Example code that shows what I want to achieve (with nasty any):

here

1 Answer 1

1

First of all, there is no dynamic Enums.

It is better to use immutable objects instead of enums, because have issues with number values.

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

It is hard to make reduce in TS without type casting (as operator)

Playground

Sign up to request clarification or add additional context in comments.

1 Comment

It's insanity that there isn't an easier way to manipulate enums!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.