- Mastering TypeScript 3
- Nathan Rozentals
- 331字
- 2021-07-02 12:42:50
Optional properties
Interface definitions may also include optional properties, similar to the way that functions may have optional properties. Consider the following interface definition:
interface IOptionalProp { id: number; name?: string; }
Here, we have defined an interface named IOptionalProp, which has an id property of type number, and an optional property called name that is of type string. Note how the syntax for optional properties is similar to what we have seen for optional parameters in function definitions. In other words, the ? character after the name property is used to specify that this property is optional. We can therefore use this interface definition, as follows:
let idOnly : IOptionalProp = { id: 1 }; let idAndName : IOptionalProp = { id: 2, name : "idAndName" }; idAndName = idOnly;
Here, we have two variables, both of which are implementing the IOptionalProp interface. The first variable, named idOnly, is just specifying the id property. This is valid TypeScript, as we have marked the name property of the IOptionalProp interface as optional. The second variable is named idAndName, and is specifying both the id and name properties. Note the last line of this code snippet. Because both variables are implementing the IOptionalProp interface, we are able to assign them to each other. Without using an interface definition that has optional properties, this code would normally have caused an error.
If you are using an editor that has support for TypeScript, you should start to see some autocomplete or IntelliSense options popping up as you work with interfaces. This is because your editor is using TypeScript's language service to automatically pick up what type you are working with, and what properties and functions are available, as follows:
Here, we can see that the VSCode editor is using IntelliSense to automatically show us what properties are available on the idOnly variable. As it is defined as implementing the IOptionalProp interface, it has two available properties, which are shown by the editor.