define optional properties in an interface in typescript

To define optional properties in an interface in TypeScript, you can use the ? symbol after the property name.

index.ts
interface MyInterface {
    requiredProperty: string;
    optionalProperty?: number;
}
87 chars
5 lines

In the example above, the optionalProperty is marked as optional with the ? symbol. This means that it can be omitted from objects that implement the MyInterface interface.

You can also use the Partial built-in utility type to create an interface with all optional properties.

index.ts
interface MyInterface {
    requiredProperty: string;
    optionalProperty?: number;
}

type MyPartialInterface = Partial<MyInterface>;
136 chars
7 lines

In the example above, MyPartialInterface type will have all the properties from MyInterface as optional.

gistlibby LogSnag