How to define optional constructor arguments with defaults in TypeScript?

Sometimes, we want to define optional constructor arguments with defaults in TypeScript.

In this article, we’ll look at how to define optional constructor arguments with defaults in TypeScript.

How to define optional constructor arguments with defaults in TypeScript?

To define optional constructor arguments with defaults in TypeScript, we can set default values for constructor parameters.

For instance, we write

export class Test {
  constructor(private foo: string = "foo", private bar: string = "bar") {}
}

We set foo‘s default value to 'foo' and bar‘s default value to 'bar' in the Test class.

Conclusion

To define optional constructor arguments with defaults in TypeScript, we can set default values for constructor parameters.