Home > OS >  Typescript: "type?" is optional in an array, while "undefined" isn't
Typescript: "type?" is optional in an array, while "undefined" isn't

Time:10-06

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

CodePudding user response:

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

For why they are different see here.

CodePudding user response:

? 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]

  • Related