0

Can I specify an array as a type in Typescript and then any subset of this array is allowed to be passed?

E.g.

type Actions = ['view', 'share', 'delete']

const concatActions = (actions: Actions) => actions.join();

concatActions(['view', 'delete']) // Works
concatActions(['share']) // Works
concatActions(['view', 'some_other_action']) // Throws type error

1 Answer 1

2

This should work

type Action = 'view' | 'share' | 'delete'
type Actions = Action[]
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way also to disallow duplicates? so that ['share', 'view', 'share'] is not allowed.
I don't think so, not TypeScript natively at least. The solution would be to prevent dupes in concatActions. You can create a new SO question and send it to me if you wonder how to do that. Let's stay on topic :)

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.