Андрей Андреев Андрей Андреев - 3 months ago 42
TypeScript Question

Final keyword in typescript?

Is there any way to make a variable available to be assigned only once? Like this

interface IFACE{
a: number;
final b: number;
}

IFACEConstructor (a: number): IFACE {
return {a: a, b: 1}
}

test = IFACEConstructor(2);
test.a = 5 //OK
test.b = 2 //Error

Answer

You could use set/get to achieve the result.

class Test {

    constructor(public a: number, private _b: number) {}

    get b(): number {
        return this._b;
    }

}

var test = new Test(2, 1);

test.a = 5 //OK
test.b = 2 //Error

test.b cannot be set because it doesn't have a setter.

TS compiler will not warn you about it, but the browser will throw an error.

Comments