define optional properties in an interface in javascript

To define optional properties in an interface in JavaScript, you can use the question mark ? operator.

Here's an example of an interface with optional properties:

index.tsx
interface Person {
  firstName: string;
  lastName: string;
  age?: number;
  occupation?: string;
}

// Usage
const john: Person = {
  firstName: 'John',
  lastName: 'Doe',
  age: 30
}

const jane: Person = {
  firstName: 'Jane',
  lastName: 'Doe',
  occupation: 'Developer'
}
278 chars
20 lines

In the above example, the Person interface has two required properties firstName and lastName, and two optional properties age and occupation. The age and occupation properties can be omitted when creating an object of the Person type, but if they are provided, their values must match their respective types number and string.

gistlibby LogSnag