如何在打字稿中实现类常量? [英] How to implement class constants in typescript?

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

问题描述

在TypeScript中,const关键字不能用于声明类属性.这样做会导致编译器出现"A类成员不能具有'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};

我正在使用打字稿1.8.有建议吗?

I'm using typescript 1.8. Suggestions?

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

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

推荐答案

TypeScript 2.0具有 修饰符:

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.

替代解决方案

另一种方法是将static关键字与readonly一起使用:

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天全站免登陆