有没有办法让一个变量只分配一次?这样地
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
有没有办法让一个变量只分配一次?这样地
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
它将从1.4开始提供,您可以查看Announcing TypeScript 1.4 article, "Let/Const" support section:
"TypeScript现在支持在'var'之外使用'let'和'const'.目前这些都需要ES6输出模式,但我们正在研究在future 的版本中放宽这一限制."
Const应按照article执行.
你可以得到TypeScript 1.4 here.
当然,"const和final不一样".问题是"有没有办法让变量只分配一次?".
常量声明必须有初始值设定项,除非在环境上下文中
写入常量是错误的
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
}
目前(2015年11月),在我看来,"const"似乎是完成上述任务的唯一方法,由现成的typescript提供.
对于那些投了反对票的人——如果你还有其他答案,请在这个帖子中与comunity分享.
Typescript 2.0中引入了readonly修饰符(感谢@basarat).You can initialize them at the point of declaration or in the constructor.
甚至可以将类属性声明为只读.你可以初始化
class Foo { readonly bar = 1; // OK readonly baz: string; constructor() { this.baz = "hello"; // OK } }
但正如《this thread》中的@RReverser所说:
像往常一样,对于所有 fresh 的东西,你需要使用npm i