英文:
How to define static variables in TypeScript
问题
我想定义一个包含常量值的数组,例如 const arr = ["a", "b"];
。然而,编译器会将其视为 string[]
。是否有一种方法可以将其保持为常量类型,使得 arr 的类型应为 ["a", "b"]
。我找到的唯一方法是像这样做:const arr: ["a", "b"] = ["a", "b"];
,但这样就像是代码重复。
英文:
I want to define an array with a constant value
e.g. const arr = ["a", "b"];
. However, the compiler will think it's string[]
. Is there is a way to make it a constant type as is so the type of arr should be ["a", "b"]
. The only way I found was to do like: const arr: ["a", "b"] = ["a", "b"];
. but it's like code duplication.
答案1
得分: 1
你可以将其定义为只读常量。请记住,常量无论如何都不能被重新赋值。
const CHOICES = ['a', 'b'] as const;
英文:
You could define it as a read-only constant. Keep in mind that a constant can never be reassigned anyways.
const CHOICES = ['a', 'b'] as const;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论