1

Say I wanted to encode an array, which could have either length 1 or 2 into typescript. Say I furthermore wanted to limit the first element in the array to be one of a specific number of strings, eg:

type fruit = 'banana' | 'apple' | 'passionfruit' | 'kiwi'

while the second key was flexible.

something like:

declare interface ObjectExample {
  fruit: fruit,
  other?: string
}

but for an array. How would I go about doing this?

1 Answer 1

1

This would be:

type ObjectExample = [fruit] | [fruit, any];

However, this will not prevent you from assigning or accessing a third element on the array. From the TS docs:

When accessing an element outside the set of known indices, a union type is used instead:

In that sense, unless you want to constrain the type of the second element, the above is equivalent to

type ObjectExample = [fruit];
Sign up to request clarification or add additional context in comments.

Comments

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.