Close

TypeScript - Interfaces with Optional Properties

[Updated: Sep 6, 2018, Created: Sep 6, 2018]

In TypeScript, the interfaces which describe objects can have optional properties.

Interfaces with optional properties are written similar to other interfaces, with each optional property denoted by a ? at the end of the property name in the declaration.

Example

optional-properties.ts

interface Person {
    name: string;
    age: number;
    phone?: string;
}

let p: Person = {name: "Ashlee", age: 29};
console.log(p);

Output

{ name: 'Ashlee', age: 29 }

If we don't use ? with property 'phone':

without-optional-properties.ts

interface Person {
    name: string;
    age: number;
    phone: string;
}

let p: Person = {name: "Ashlee", age: 29};
console.log(p);

Output

without-optional-properties.ts(7,5): error TS2322: Type '{ name: string; age: number; }' is not assignable to type 'Person'.
Property 'phone' is missing in type '{ name: string; age: number; }'.

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.0.1
Interfaces with Optional Properties Select All Download
  • typescript-interface-optional-properties
    • optional-properties.ts

    See Also