Typescript: Readonly vars getting typecast to "false" instead of "boolean"

Created on 22 Dec 2016  ·  6Comments  ·  Source: microsoft/TypeScript

TypeScript Version: 2.1.4

Code

class blah {
    private readonly _something = false;
    constructor() {
        this._something = true;
    }
}

Expected behavior:
Doesn't cause an error

Actual behavior:
Causes an error

Duplicate

Most helpful comment

class blah {
    private readonly _something: boolean;
    constructor() {
        this._something = true;
    }
}

10676

The type inferred for a const variable or readonly property without a type annotation is the type of the initializer as-is.

All 6 comments

class blah {
    private readonly _something: boolean;
    constructor() {
        this._something = true;
    }
}

10676

The type inferred for a const variable or readonly property without a type annotation is the type of the initializer as-is.

I guess "by design" is an answer. Not an answer I'd expect for this, but fair enough.

Can I ask why there are two initializers for _something ?

Because _something has a default value, and only some paths in the initializer set it. It was an easy fix to change it to "private readonly _something: boolean = false", it just seems an odd language construct. Readonly is only readonly after the end of the constructor. If anything, it feels like you should take the type as the union of all options set in the validity period, so in this case would be false|true.

This has already been discussed in https://github.com/Microsoft/TypeScript/issues/12189 in the context of https://github.com/Microsoft/TypeScript/issues/12148. The conclusion then was that this code is ambiguous, and the property should have a type annotation. in the absence of a type annotation, the compiler will use the type from the internalizer, i.e. false in this case.

Duplicate of #12148.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fwanicka picture fwanicka  ·  3Comments

Antony-Jones picture Antony-Jones  ·  3Comments

bgrieder picture bgrieder  ·  3Comments

remojansen picture remojansen  ·  3Comments

MartynasZilinskas picture MartynasZilinskas  ·  3Comments