1

Is there a way to short form this statement:

Array<{ [enum.example1]: Example } | { [enum.example2]: Example } | ...>
// or equivalent
({ [enum.example1]: Example } | { [enum.example2]: Example } | ...)[];

So it is more succinct like { [key: string]: Example }, but uses a string enum to restrict the possible keys:

For example, these don't appear to work:

{ [enum]: Example }[];
// or
{ [key: enum]: Example }[];

1 Answer 1

1

You can use the same syntax as for a limited set of string literals:

{ [key in MyEnum]?: Example }[]

See this stackblitz for a demo.

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

3 Comments

Is it possible do something similar with an interface like in this example stackblitz.com/edit/angular-gmq9qp?embed=1&file=src/app/…? Seems to indicate an error, and if I change the keys in test to something outside the enum it seems to accept it.
According to the error message, it appears to be disallowed in an interface declaration. I don't know if there is a workaround in that case.
Thanks, you're right. Looks like it isn't. You need to use an alias like export type Alias = { [key in Example]: string; }, or wait for github.com/Microsoft/TypeScript/pull/26797.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.