My problem is similar to this:
Type Name = {firstName: string, lastName: string}
class NameClass {
public _name: Name | null;
constructor() {
this._name = null;
}
// or any function
public set name(name: Name) {
this._name = name;
}
public printName() {
if (!this._name) this.name = { firstName: "should not", lastName: "be null" };
// v Object may be null even though I just set it ^
console.log(this._name.firstName);
}
}
I’m aware I can simply use the " ! " assertion to get around this or can create a separate function to make sure that the object is not null, but I’m looking for a way to tell typescript that the function will set the property.
There is a solution proposed in question
but I find this kind of hacky and doesn’t really solve the problem. The post was also 4 years ago, so I’m hoping there is a better way to fix this?
2
Answers
If im not mistaken, the problem is not telling typescript "how to do it" – it is simply not possible. The class cannot and will never know, what nullable property was set in what function (or some other way). The whole point of having a nullable property is to have the opportunity to set that property to null. Even after setting the property, it may return back to null (e. g. through another function).
A work around would be having that property set to defalt string values (
""
) in the constructor.Also as a side-note, it is not recommendet to have a public property start with an underscore. Normally, only
private
fields are named like that.Have you considered initializing the _name property in the constructor?
Typescript is okay with that, because that way _name is always set.