Optional interfaces in TypeScript

Does the following TypeScript look like it will compile to JavaScript without errors?


Spoiler: it does. Because the option1 and option2 properties of IOptions are optional, it is valid to assign a variable to a IOptions type that does not provide those properties.

I realised this recently when working with the DefinitelyTyped highcharts definition file and wondered why I could assign a HighchartsAxisOptions[] variable to a property of type HighchartsAxisOptions. All of the properties in the HighchartsAxisOptions type are optional and so it was valid.

In these cases we aren’t benefitting from any compiler checks, because there aren’t any that can be done. The benefits we do get are a specification of what properties are may be provided and the types of those properties, which can be used as suggestions or auto-complete options in an IDE. .

Optional interfaces in TypeScript