1

I would like to create a valid type for an array of number where any element can be null except the first one.

My best try so far cannot handle array of any size:

type NulNum = number | null
type MyArray = 
    | [number, NulNum]
    | [number, NulNum, NulNum]
    | [number, NulNum, NulNum, NulNum]
    | [number, NulNum, NulNum, NulNum, NulNum]
    // ...


// valid cases, should compile properly
let a: MyArray = [1, null]
a = [1, 1]
a = [1, 1, null]
a = [1, 1, null, null]

// invalid cases, should trigger a compilation error
a = [null, 1]
a = [null, null]
0

1 Answer 1

1

Nevermind, I found the answer based on suggested linked stackoverflow questions: https://stackoverflow.com/a/56814700/2523414

type MyArray = [number, ...(number | null)[]]


// valid cases, should compile properly
let a: MyArray = [1, null]
a = [1, 1]
a = [1, 1, null]
a = [1, 1, null, null]

// invalid cases, should trigger a compilation error
a = [null, 1]
a = [null, null]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.