In TypeScript, interfaces are used to define the structure of objects, but they do not provide default values for properties.

However, you can define optional properties using the ? operator, and you can also set default values for object properties when you define the object.

Here’s an example of how we can define an interface with optional properties and set default values for the properties:

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

In this example, the Person interface defines three properties: name, age, and gender. The age and gender properties are optional, as indicated by the ? operator.

If we want to set default values for required properties, we can use a type assertion to cast the value to the expected type:

export interface Person {
  name: string;
  age: number;
  gender: string;
}

export const defaultsPerson = {
  name: 'John',
  age: 30,
  gender: 'male',
} as Person;

In this example, the “defaultsPerson” object has the same properties as the Person interface, but we’re using a type assertion to tell TypeScript that the object should be treated as a Person object.

Alternative:

To set up a default value with an interface, we can also use the Typescript Pick Utility type like so:

interface IPerson {
    name: string;
    role: string;
}

const defaults: Pick<IPerson, 'role'> = {
    role: 'user'
}

const person: IPerson = {
    ...defaults,
    name: 'Tim'
}

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *