An optional method is a method property that a shape type or interface permits an object or class to omit. Write a question mark after the method name and before its parameter list, such as hasFeature?(Feature): boolean. section 10.2.2 section 11.4.3
Account for these behaviors when using optional methods:
- Objects without the method still match the shape or interface, so different object types can share one collection. section 10.2.2 section 11.4.3
- An omitted method is undefined, just like an omitted optional property, and invoking it without a check can produce a runtime TypeError. section 10.2.2
- With strictNullChecks enabled, the compiler rejects calls that might target an undefined method. section 10.2.2
- Check the method before calling it; a conditional expression can provide a fallback when the method is absent. section 10.2.2 section 11.4.3
Checking a product feature
A product collection can contain objects with or without hasFeature. The safe call is: products.forEach(prod => console.log(prod.hasFeature ? prod.hasFeature(Feature.Waterproof) : "false")); This reports false for products without the method and true for an umbrella that implements it. section 10.2.2
Listing 10.10 Checking for an optional method in the index.ts file in the src folder
enum Feature { Waterproof, Insulated }
let hat = { name: "Hat", price: 100 };
let gloves = { name: "Gloves", price: 75 };
let umbrella = { name: "Umbrella", price: 30,
hasFeature: (feature) => feature === Feature.Waterproof };
let products: { name: string, price?: number,
hasFeature?(Feature): boolean }[]
= [hat, gloves, umbrella];
products.forEach(prod => console.log(`${prod.name}: ${prod.price} ` +
`${ prod.hasFeature ? prod.hasFeature(Feature.Waterproof) : "false" }`
));
Inspect the complete TypeScript listing showing an optional hasFeature method, strict existence checking, and product output. section 10.2.2
