In TypeScript there are several ways to declare a property with undefined
value: adding | undefined
in the property type
or using optional property syntax (?
after its name). Use | undefined
syntax when you want to be explicit that an object has
that property, in that case TypeScript compiler will not allow omitting it:
interface Person {
name: string;
address: string | undefined;
}
let John = { name: "John" }; // will not compile
let John = { name: "John", address: undefined }; // will compile, we want to be explicit when person does not have home
Use optional property syntax for properties holding some additional information.
interface Person {
name: string;
pet?: string;
}
let John = { name: "John" }; // will compile
let John = { name: "John", pet: undefined }; // will compile, there is no pet like for the object on previous line
let John = { name: "John", pet: "Benji" }; // will compile
Using | undefined
for optional property is redundant, it can be omitted without change to the actual type. Still if you want to force
the property in the object consider using only | undefined
without ?
.
Noncompliant Code Example
interface Person {
name: string;
address? : string | undefined; // Noncompliant, "?" should be removed
pet?: Animal | undefined; // Noncompliant, "undefined" should be removed
}
Compliant Solution
interface Person {
name: string;
address: string | undefined;
pet?: Animal;
}