Final keyword in typescript?

Andrei Andreev picture Andrei Andreev · Feb 14, 2015 · Viewed 36.1k times · Source

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

TSV picture TSV · Feb 14, 2015

It will be available since 1.4, you can check the Announcing TypeScript 1.4 article, "Let/Const" support section:

"TypeScript now supports using ‘let’ and ‘const’ in addition to ‘var’. These currently require the ES6 output mode, but we’re are investigating relaxing this restriction in future versions."

Const should be implemented according to the article.

You can get TypeScript 1.4 here.

Update 1

Of course, "const is not the same as final". The question was "Is there any way to make a variable available to be assigned only once?". So, according this documentation:

Const declarations must have an initializer, unless in ambient context

It is an error to write to a Const

const c = 0;
console.log(c); // OK: 0

c = 2; // Error
c++; // Error

{
    const c2 = 0;
    var c2 = 0; // not a redeclaration, as the var is hoisted out, but still a write to c2
}

And, for now (Nov, 2015) "const" seems to me the only way, given by typescript out-of-the-box, to accomplish the above task.

For those, who downvoted - if you have another answer, please, share it in this thread with comunity.

Update 2: readonly

The readonly modifier (thanks to @basarat) has been introduced in Typescript 2.0. You can initialize them at the point of declaration or in the constructor.

You can even declare a class property as readonly. You can initialize them at the point of declaration or in the constructor as shown below:

class Foo {
    readonly bar = 1; // OK
    readonly baz: string;
    constructor() {
        this.baz = "hello";  // OK
    }
}

But as said @RReverser in this thread:

As usual with all the fresh stuff, you need to use npm i typescript@next to get the latest compiler with experimental features included.