Reputation: 3749
The code:
class Cat extends Animal { tag! : 'cat' }
What does "!" mean after tag
declaration? How is it different from just tag
?
Upvotes: 5
Views: 1189
Reputation: 1926
Let's look at an example - imagine we have the following code:
interface Animal {
tag: string;
}
class Cat implements Animal { tag: 'cat' }
class AnimalClass {
tag: string | undefined;
}
class Dog extends AnimalClass { tag: 'dog' }
Both code snippets would throw the following: Property 'tag' has no initializer and is not definitely assigned in the constructor.(2564)
.
This is a feature of TypeScript added in 2.7.2 where it includes a strict class check, where all properties should be declared inside it's constructor.
By adding a bang sign !
, you will override this behavior and tell the compiler you "know", that it is being initialized correctly and won't be undefined later on.
Also you can disable it by setting "strictPropertyInitialization": false
inside your compiler options. Or you initialize the property where it should be initialized (according to TypeScript):
class Dog extends AnimalClass {
tag: string;
constructor() {
super();
this.tag = "";
}
}
Upvotes: 6