What does '?' indicate in a TypeScript parameter name?

What does the question mark (?) signify in a TypeScript parameter name? For example, in the following TypeScript class:

export class Thread { id: string; lastMessage: Message; name: string; avatarSrc: string;

constructor(id?: string, name?: string, avatarSrc?: string) { this.id = id || uuid(); this.name = name; this.avatarSrc = avatarSrc; } }

In the constructor, what is the purpose of the question mark in the parameter id?, and how does it relate to TypeScript?

Hey Kusha,

Type Checking and Default Values: The optional parameter allows for type checking where you can handle cases where the parameter might be undefined. It also facilitates setting default values or performing conditional logic based on whether the parameter is provided. constructor(id?: string, name?: string, avatarSrc?: string) { this.id = id || uuid(); // Sets default id if not provided this.name = name || ‘Default Name’; // Sets a default name if not provided this.avatarSrc = avatarSrc || ‘default-avatar.png’; // Sets a default avatar source if not provided } Here, default values are used if the optional parameters are not supplied.

Hello Kusha,

Impact on Function Overloading: Using optional parameters can simplify function overloading scenarios by reducing the number of overloaded signatures needed. You can define a single function signature with optional parameters rather than multiple overloaded signatures. Example:

function createThread(id?: string, name?: string, avatarSrc?: string): Thread { return new Thread(id, name, avatarSrc); } This approach avoids the need for multiple overloaded versions of the createThread function.

In summary, the typescript question mark is used to mark parameters as optional, allowing for flexibility in function and constructor arguments while providing default values or conditional logic based on the presence or absence of these parameters.