Optional properties

One thing about interfaces, though, is that the defined properties/methods of an interface must be supplied when creating the values that are typed with that interface. Basically, I am saying that we must adhere strictly to the contract established with an interface.

Therefore, the following is incorrect and will throw an error:

interface OptionBag { show: boolean, container: string}let options: OptionBag = {show: true}; // Error

We can make container optional; we use the question mark literal, as seen in a previous example:

interface OptionBag { show: boolean, container?: string}let options: OptionBag = {show: true}; // No Error

Be careful, though, to account for when the optional parameter is not supplied. The following ...

Get TypeScript 2.x for Angular Developers now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.