Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 901
Andrei Andreev Avatar asked Feb 14 '15 08:02

Andrei Andreev


People also ask

Is there final in TypeScript?

To make a variable final in TypeScript, we can use the readonly keyword.

What is final keyword?

The final keyword is a non-access modifier used for classes, attributes and methods, which makes them non-changeable (impossible to inherit or override). The final keyword is useful when you want a variable to always store the same value, like PI (3.14159...). The final keyword is called a "modifier".


1 Answers

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.

like image 174
TSV Avatar answered Sep 23 '22 16:09

TSV