Categories
TypeScript Answers

How to define optional constructor arguments with defaults in TypeScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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