1

Is the following somehow possible? I want to require the 'foo' literal, but allow the array to be any shape (i.e. I can't use an X-length tuple with pre-defined positions)

type requireFoo = ???

const works: requireFoo = ['bar','foo'] //Should work
const notWork: requireFoo = ['tar', 'bar'] //Should not work

Here's a playground template

1
  • 2
    If there's a problem in particular that you're trying to solve, you might want to post that as a question instead so that we might be able to provide a more ergonomic solution by changing both the javascript and the typings. Commented Jan 20, 2021 at 17:54

1 Answer 1

2

It's a strange requirement. If you require foo occurs at the end or start of the tuple you can do this:

type requireFoo = [...any[], 'foo']

const works: requireFoo = ['bar', 'foo' as const] // Good 
const notWork: requireFoo = ['tar', 'bar' as const] // Bad 

note: Rest arguments in the start of the tuple as shown above are only available in typscript 4.2 beta.

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.