Reputation: 387
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
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:
a: string = '';
constructor() { this.a = ''; }
Upvotes: 0
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