Skip to main content

Const 表达式

有时指定字面量表达式是不可变的很有用。在这种情况下,你可以使用 as const 修饰符注释表达式。我们将这些表达式称为 const 表达式。

¥Sometimes it is useful to specifiy that a literal expression is expected to be immutable. In such cases, you can annotate the expression with the as const modifier. We refer to these expressions as const-expressions.

Const 表达式的类型

¥Typing for Const Expressions

const 表达式的推断类型是原始值的 单例类型 和容器类型的只读版本。数组字面量被推断为元组类型。

¥The inferred type of const-expressions is the singleton type for primitive values and the read-only versions for container types. Array literals are inferred as tuple types.

以下是一些原始值的示例:

¥Here are some examples of primitive values:

42 as const; // inferred type is 42

"hello" as const; // inferred type is "hello"

容器变为只读,修饰符被深度应用

¥Containers become read-only and the modifier is applied deeply

{ f: 42 } as const; // {+f: 42}

[42, "hello"] as const; // $ReadOnly<[42, "hello"]>

{ f: { g: 42 } } as const; // {+f: {+g: 42}}

请注意,修饰符的效果不会通过变量持续存在。例如在

¥Note that the effect of the modifier does not persist through variables. For example in

const nonConstObject = { g: 42 };
const constObject = { f: nonConstObject } as const;

nonConstObject 的类型将是 {g: number}constObject 的类型将是 {+f: {g: number}}。换句话说,只有顶层属性 prop 是只读的。

¥the type of nonConstObject will be {g: number} and the type of constObject will be {+f: {g: number}}. In other words, only the top-level property prop will be read-only.

最后,将 as const 应用于非字面量表达式是错误的:

¥Finally, it is an error to apply as const to non-literal expressions:

1const x = 1;2const y = x as const;

典型的 const 表达式示例

¥Typical const-expression example

const 表达式有用的常见模式是在不希望发生修改的枚举类结构中。例如

¥A common pattern where const-expressions are useful is in enum-like structures that are not expected to be mutated. For example

export const STATUS = {
INIT: 'INIT',
LOADING: 'LOADING',
SUCCESS: 'SUCCESS',
ERROR: 'ERROR',
} as const;

STATUS.INIT 的类型是 "INIT"STATUS.LOADING 的类型是 "LOADING",依此类推。

¥The type of STATUS.INIT is "INIT", the type of STATUS.LOADING is "LOADING" and so on.

使用此定义,还可以有效地将各个字段的值提升为类型注释。例如

¥With this definition it is also possible to effectively lift the values of the various fields to type annotations. For example

type State =
| { +kind: typeof STATUS.INIT; }
| { +kind: typeof STATUS.LOADING; progress: number; }
| { +kind: typeof STATUS.SUCCESS; result: string; }
| { +kind: typeof STATUS.ERROR; msg: string; };

如果不使用 as const,则 typeof STATUS.INIT 类型将是 string,这将使其不适合作为不相交联合中的区分标记。

¥Without the use of as const the type typeof STATUS.INIT would be string, which would make it unsuitable as a distinguishing tag in a disjoint union.

采用 as const 语法

¥Adoption of as const syntax

要使用 as const 语法,你需要升级基础架构:

¥To use the as const syntax, you need to upgrade your infrastructure: