如何实现类常量? [英] How to implement class constants?

查看:28
本文介绍了如何实现类常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 TypeScript 中,const 关键字不能用于声明类属性.这样做会导致编译器报错类成员不能有‘const’关键字."

In TypeScript, the const keyword cannot be used to declare class properties. Doing so causes the compiler to an error with "A class member cannot have the 'const' keyword."

我发现自己需要在代码中明确指出不应更改属性.如果在声明属性后尝试为其分配新值,我希望 IDE 或编译器出错.你们是如何做到这一点的?

I find myself in need to clearly indicate in code that a property should not be changed. I want the IDE or compiler to error if I attempt to assign a new value to the property once it has been declared. How do you guys achieve this?

我目前使用的是只读属性,但我是 Typescript(和 JavaScript)的新手,想知道是否有更好的方法:

I'm currently using a read-only property, but I'm new to Typescript (and JavaScript) and wonder whether there is a better way:

get MY_CONSTANT():number {return 10};

我使用的是 typescript 1.8.建议?

I'm using typescript 1.8. Suggestions?

PS:我现在使用的是 typescript 2.0.3,所以我接受了 David 的回答

PS: I'm now using typescript 2.0.3, so I've accepted David's answer

推荐答案

TypeScript 2.0 具有 readonly 修饰符:

TypeScript 2.0 has the readonly modifier:

class MyClass {
    readonly myReadOnlyProperty = 1;

    myMethod() {
        console.log(this.myReadOnlyProperty);
        this.myReadOnlyProperty = 5; // error, readonly
    }
}

new MyClass().myReadOnlyProperty = 5; // error, readonly

它不完全是一个常量,因为它允许在构造函数中赋值,但这很可能没什么大不了的.

It's not exactly a constant because it allows assignment in the constructor, but that's most likely not a big deal.

替代解决方案

另一种方法是在 readonly 中使用 static 关键字:

An alternative is to use the static keyword with readonly:

class MyClass {
    static readonly myReadOnlyProperty = 1;

    constructor() {
        MyClass.myReadOnlyProperty = 5; // error, readonly
    }

    myMethod() {
        console.log(MyClass.myReadOnlyProperty);
        MyClass.myReadOnlyProperty = 5; // error, readonly
    }
}

MyClass.myReadOnlyProperty = 5; // error, readonly

这样做的好处是不能在构造函数中赋值,只能存在于一处.

This has the benefit of not being assignable in the constructor and only existing in one place.

这篇关于如何实现类常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆