Search⌘ K
AI Features

Optional Properties and Prefixing Interface Names

Explore how to define optional properties in TypeScript interfaces using the question mark syntax and understand why prefixing interface names with I is debated. Learn the difference in interface usage between TypeScript and languages like C# and decide on naming conventions that fit your development team.

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:

TypeScript 4.9.5
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:

TypeScript 4.9.5
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 ...