In TypeScript, using a question mark to indicate an optional property will result in an error when transpiled to JavaScript.
The use of | undefined
in type definitions is redundant because all properties can inherently have undefined assigned as their value.
For example, defining a type like:
type A = {a?: string, b: string}
allows you to create a variable without specifying property a
:
let x: A = { b: 'some value' };
Declaring type A = {a: string | undefined}
serves no real purpose compared to type A = {a: string}
, since the presence of property a
is still required and strings can already be assigned undefined.
Attempting let x: A = {}
will result in an error due to missing property a
, while assigning a: undefined
with let x: A = { a: undefined }
is allowed with type A = {a: string}
.
This renders the use of | undefined
unnecessary, as any property can accept undefined values regardless.