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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.