TypeScript is complaining about an uninitialized class property, even though it appears to be properly assigned.
Here's a minimum reproducible example:
type Config = {
color: string;
}
class Toto {
color: string;
constructor(config: Config) {
this.setConfig(config);
}
setConfig(config: Config) {
this.color = config.color;
}
}
The compiler underlines the color property definition and throws the following error:
Property 'color' has no initializer and is not definitely assigned in the constructor.
The issue appears to be with using the setConfig method to set the value of color, since the following code produces no compiler errors:
type Config = {
color: string;
}
class Toto {
color: string;
constructor(config: Config) {
this.color = config.color;
}
}
This problem is I want to be able to use the setConfig method to set class properties to different values during the lifetime of a class instance. I don't want to have to repeated the same code within both my constructor and setConfig method just to get around a TS compiler issue.
Does anyone know why the compiler can't see that the class variable is properly being set in the constructor?
setConfigcould be overridden in a subclass and that override could choose to not setthis.color. The only way TypeScript can guarantee thatthis.coloris set is by requiring it to be set directly in the constructor.nullor empty string or a similar default value.Totoand overide it with a differentsetConfigmethod and then that new method would be used by theTotoclass constructor? @Dai