1

Two signatures I thought were the same are behaving differently from each other:

type FooType = [ string, number? ]
const fooAr = [ "foo" ] as FooType // compiles
type BarType = [ string, number | undefined ]

// Conversion of type '[string]' to type 'BarType' may be a mistake because neither type sufficiently overlaps with the other.
const barVar = [ "bar" ] as BarType

I wouldn't mind except I'm inferring the type from a library and can't change the signature. Is this how Typescript is supposed to behave?

== Edit

Was hoping it followed the object type behavior:

type FooType = { foo: string, bar: string | undefined }
const fooOjb = { foo: "abc" } as FooType // compiles
3
  • 1
    Yep. Not existing and existing with a value of undefined are different. Commented Oct 5, 2022 at 22:35
  • 1
    About your update: that only works because it's a type assertion: tsplay.dev/mZXnEw. See this question for the differences and nuances. Commented Oct 5, 2022 at 22:44
  • That makes so much more sense thank you for the link! Commented Oct 5, 2022 at 22:58

2 Answers 2

2

? and undefined are not interchangable.


type FooType = [ string, number? ] means that the array can look like this:

["hello"] or ["hello", 123]


type BarType = [ string, number | undefined ] means that the array can look like this:

["hello", undefined] or ["hello", 123]

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

3 Comments

Important to note that this behavior is also seen in objects, but you can turn on exactOptionalPropertyTypes to change that.
Totally right. Thanks for pointing it out @caTS
Dang! Exactly why I thought it'd behave that way, thanks
1

FooType is using an optional, where as BarType is using undefined.

For why they are different see here.

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.