Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript not recognising initialising via a setter

Tags:

typescript

In the following example:

class Foo {
    private _bar: number;

    constructor(bar: number) {
        this.bar = bar;
    }

    set bar(bar: number) {
        this._bar = bar;
    }
}

TypeScript complains that

Property '_bar' has no initializer and is not definitely assigned in the constructor.

I'd have assumed TypeScript would be intelligent enough to detect that the property is being set via a setter, but apparently not.

I can fix this by changing the assignment in the constructor to set this._bar itself, but it's good practice for a class to use its own getters and setters and this fix would be bypassing that. Are there any other ways of resolving this?

like image 213
cb7 Avatar asked Sep 14 '25 18:09

cb7


1 Answers

If the compiler can't figure out that a property is properly initialized, and if you are sure that is, you can tell the compiler this via a definite assignment assertion modifier (!) on the property declaration:

private _bar!: number; // definitely set in constructor, no error now

Obviously it would be better if the compiler could verify this for you, but there's little hope of having this happen since the initialization happens inside what amounts to a function/method call, and the compiler basically assumes that such calls don't mutate any state. This assumption isn't always correct (e.g., it's wrong right now) but it's pragmatic; fully analyzing all the side effects of a function/method call would be impossible to implement feasibly (it would be essentially simulating the program being run on all possible inputs), so any analysis would have to be heuristic and necessarily incomplete or unsound. See microsoft/TypeScript#9998 for a quite lengthy discussion of the tradeoffs involved.

Okay, hope that helps; good luck!

Playground link to code

like image 189
jcalz Avatar answered Sep 17 '25 09:09

jcalz