...

/

Optional Properties and Prefixing Interface Names

Optional Properties and Prefixing Interface Names

Learn about optional interface properties, view the transpiled JavaScript output, and learn about the debate over interface name prefixes in TypeScript.

Introduction to optional properties

Interface definitions may also include optional properties similar to functions that specify optional parameters using the question mark (?) syntax.

Consider the following interface:

interface IOptional {
id: number;
name?: string;
}
Optional properties in TypeScript interface

Here, we have an interface named IOptional, which has defined an id property of type number and an optional property named name of type string.

We can now define objects as follows:

interface IOptional {
id: number;
name?: string;
}
let optionalId: IOptional = {
id: 1,
};
// 'optionalId' is an object of type 'IOptional' with only the required 'id' property set to 1
let optionalIdName: IOptional = {
id: 2,
name: "optional name",
};
// 'optionalIdName' is an object of type 'IOptional' with both required 'id' property set to 2 and optional 'name' property set to "optional name"
Optional properties

Here, we have two objects named optionalId and optionalIdName that both implement the IOptional interface.

As the name property has been marked optional, both of these objects correctly implement the interface.

Interfaces are compiled away

Interfaces do not generate any JavaScript code. This ...