In TypeScript, there are two ways to define properties or parameters that are potentially undefined
:
- Union with
undefined
: Adding | undefined
in the property type makes the property required, but can be
undefined
. Use this syntax when you want to be explicit that an object should provide that property, in which case the TypeScript
compiler will not allow omitting it.
interface Person {
name: string;
address: string | undefined;
}
let John = { name: "John", address: undefined };
- Optional property syntax (
?
after its name): The property is optional, which means that an object can omit it and let the
TypeScript compiler provide it as being undefined
.
interface Person {
name: string;
address?: string;
}
let John = { name: "John" };
This rule checks for optional property declarations that use both the ?
syntax and unions with undefined
.
interface Person {
name: string;
address?: string | undefined; // Noncompliant: using both syntaxes is redundant
}
Choose one of the syntaxes to declare optional properties and remove the other one. Consider using only | undefined
if you want to
make the property explicit in the object.
interface Person {
name: string;
address?: string;
}
The rule does not raise any issues when the TypeScript compiler option exactOptionalPropertyTypes
is enabled because this option
ensures that undefined
does not become redundant in this context.