如何在TypeScript中定义静态变量

huangapple go评论124阅读模式
英文:

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;

huangapple
  • 本文由 发表于 2023年7月31日 21:55:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定