Dakito
Dakito

Reputation: 387

Type with default value

Is there any way to create type which will be declared with default value. Instead writing the same declaration:

class Test{
a: string = '';
b: string = '';
c: string = '';
...
}

[BTW. it look's bad] to write only type

class Test{
a: type_with_default_value;
b: type_with_default_value;
c: type_with_default_value;
}

Much prettier

Upvotes: 1

Views: 979

Answers (2)

syntagma
syntagma

Reputation: 24294

Is there any way to create type which will be declared with default value

No, it is not possible because of this: you declare o variable, not define it, therefore you are not actually setting any value, which you have to do somewhere.

There are languages, which do default initialization for some cases (C++ is an example) but TypeScript can only default-initialize to undefined when --strictPropertyInitialization flag is not used

Therefore, you are left with the following options:

  1. What you are doing now: a: string = '';
  2. Initialization in the constructor: constructor() { this.a = ''; }

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

You can define a constant with the default value, and let inference take care of the type

const noString = '' // you can specify the type of the const 
class Test {
  a = noString;
  b = noString;
  c = noString;

}

In Typescript types and values share differ universes. There is no way for a type annotation to also assign a default value to the field.

Upvotes: 1

Related Questions