TypeScript Optional and Undefined
There is a slight difference between property?: string
and property: string | undefined
.1 2 3
property?: string
says the property may not exist, and - if the exactOptionalPropertyTypes flag 4 is not set - may have the value undefined.property: string | undefined
says the property will exist, and may have the value of undefined.property?: string | undefined
says the property may not exist, and may have the value of undefined.
Best Practice
Enable the exactOptionalPropertyTypes flag.
Use property: string | undefined
to make sure a property is always included and deliberately set to undefined This may be useful to make sure a property isn't accidentally forgotten.
This is especially important for libraries to communicate how they check a property is undefined. For example o.x === undefined
or Object.hasOwn(o, "x")
5 or Object.prototype.hasOwnProperty(o, "x")
6
Example
Open Example in TypeScript Playground
interface A {
property?: number;
}
interface B {
property: number | undefined
}
//
// A example
//
const a:A = {
};
const a2: A = {
property: undefined
};
//
// B example
//
// Invalid
//const b: B = {
//};
const b = {
property: undefined
};
console.log(a); // {}
console.log(b); // {"property": undefined}