Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

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
question from:https://stackoverflow.com/questions/28513780/final-keyword-in-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...