Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: is short hand for union of undefined and string is optional property type?

Tags:

typescript

I find it is weird, so can someone confirm either these two are the same.

interface TypeA {
 time: string | undefined;
}

interfaceTypeB {
 time?: string;
}
like image 246
roger Avatar asked Oct 20 '25 20:10

roger


1 Answers

They are similar, but not identical. Try the following for example:

interface TypeA {
 time: string | undefined;
}

interface TypeB {
 time?: string;
}

const exampleA: TypeA = {}

const exampleB: TypeB = {}

exampleA will give an error, because it needs the undefined time to be explicit. Merely omitting the property does not suffice. exampleB gives no error.

Playground link

like image 55
Nicholas Tower Avatar answered Oct 23 '25 11:10

Nicholas Tower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!