An optional property lets an object shape or interface accept objects that omit that property. Add a question mark after the property name, such as `waterproof?: boolean`. Required properties must still be present. section 10.2.2 section 11.4.3
When an optional property is read:
- An object may define the property or leave it absent. section 10.2.2
- The value is the object's value when present, otherwise `undefined`. section 10.2.2
- Optional interface members allow implementing classes to omit properties or methods, but callers must check before using them. section 11.4.3
Optional properties in an object shape
let hat = { name: "Hat", price: 100 };\nlet umbrella = { name: "Umbrella", price: 30, waterproof: true };\n\nlet products: { name: string, price?: number, waterproof?: boolean }[]\n = [hat, umbrella];\n\nproducts.forEach(prod =>\n console.log(`${prod.name}: ${prod.waterproof}`));\n\n// Hat: undefined\n// Umbrella: true section 10.2.2
Checking an optional interface method
interface Person {\n name: string;\n getDetails(): string;\n getDogDetails?(): string;\n}\n\nif (item.getDogDetails) {\n console.log(item.getDogDetails());\n}\n\nOnly objects that provide `getDogDetails` invoke it; other implementations use the required `getDetails` member alone. section 11.4.3
Listing 10.7 Using an optional property in the index.ts file in the src folder
let hat = { name: "Hat", price: 100 };
let gloves = { name: "Gloves", price: 75 };
let umbrella = { name: "Umbrella", price: 30, waterproof: true };
let products: { name: string, price?: number, waterproof?: boolean }[]
= [hat, gloves, umbrella];
products.forEach(prod =>
console.log(`${prod.name}: ${prod.price} `
+ `Waterproof: ${ prod.waterproof }`));
Inspect the complete product example showing omitted and defined optional properties and their runtime values. section 10.2.2

