all attributes optional in typescript

In TypeScript, to make all attributes optional in an interface, you can simply add a ? after each attribute name.

index.ts
interface ExampleInterface {
  attribute1?: string;
  attribute2?: number;
  attribute3?: boolean;
}
101 chars
6 lines

This will allow instances of ExampleInterface to be created without providing any attribute values.

If you want some attributes to be required and some to be optional, you can omit the ? for the required attributes.

index.ts
interface ExampleInterface {
  attribute1: string;
  attribute2?: number;
  attribute3: boolean;
}
99 chars
6 lines

In this example, attribute1 and attribute3 are required, while attribute2 is optional.

gistlibby LogSnag