详细介绍 TypeScript 中的 ‘as const’

在 TypeScript 中使用 as const 时,我们可以将对象的属性或数组的元素设置为只读,向语言表明表达式中的类型不会被扩大(例如从 42 到数字)。

function sum(a: number, b: number) {
  return a + b;
}

// ?️ const arr: readonly [3, 4]
const arr = [3, 4] as const;

console.log(sum(...arr)); // ?️ 7

我们创建了一个 sum 函数,它以 2 个数字作为参数并返回总和。

但是,我们在数组中有数字,所以我们需要一种方法来告诉 TypeScript 这个数组只能有 2 个类型为 number 的元素。 这是我们在 TypeScript 中使用 const 断言的时候。

const 断言使我们能够告诉 TypeScript 数组的类型不会被扩展,例如 从 [3, 4] 到 number[]

示例中的数组成为只读元组,因此其内容无法更改,我们可以在调用 sum 函数时安全地解压缩这两个数字。

如果你试图改变数组的内容,你会得到一个错误。

function sum(a: number, b: number) {
  return a + b;
}

// ?️ const arr: readonly [3, 4]
const arr = [3, 4] as const;

// ⛔️ ERROR: Property 'push' does not exist on type
//  'readonly [3, 4]'
arr.push(5);

实际编译运行如下

TypeScript as const ERROR

我们使用了一个 const 断言,因此该数组现在是一个只读元组,其内容无法更改,并且尝试这样做会在开发过程中导致错误。

如果我们尝试在不使用 const 断言的情况下调用 sum 函数,我们会得到一个错误 “Error: A spread argument must either have a tuple type or be passed to a rest parameter.”

function sum(a: number, b: number) {
  return a + b;
}

// ?️ const arr: readonly [3, 4]
const arr = [3, 4];

// ⛔️ Error: A spread argument must either have a tuple
// type or be passed to a rest parameter.
console.log(sum(...arr)); // ?️ 7

实际编译运行结果如下

详细介绍 TypeScript 中的 'as const'

TypeScript 警告我们,没有办法知道 arr 变量的内容在其声明和 sum() 函数被调用之间没有改变。

当使用 const 断言时,数组变为只读元组,因此 TypeScript 可以确保其内容不会在其声明和函数调用之间发生变化。

如果我们不喜欢使用 TypeScript 的枚举构造,也可以使用 const 断言作为枚举的替代品。

// ?️ const Pages: {readonly home: '/'; readonly about: '/about'...}
export const Pages = {
  home: '/',
  about: '/about',
  contacts: '/contacts',
} as const;

如果我们尝试更改对象的任何属性或添加新属性,则会收到错误消息。

// ?️ const Pages: {readonly home: '/'; readonly about: '/about'...}
export const Pages = {
  home: '/',
  about: '/about',
  contacts: '/contacts',
} as const;

// ⛔️ Error: Cannot assign to 'about', because it is
// a read-only property
Pages.about = 'hello';

// ⛔️ Error: Property 'test' does not exist on type ...
Pages.test = 'hello';

实际编译运行结果如下

详细介绍 TypeScript 中的 'as const'

然而,应该注意的是,const 上下文不会将表达式转换为完全不可变的。

const arr = ['/about', '/contacts'];

// ?️ const Pages: {readonly home: '/', menu: string[]}
export const Pages = {
  home: '/',
  menu: arr,
} as const;

// ✅ Works
Pages.menu.push('/test');

menu 属性引用了一个外部数组,我们可以更改其内容。

如果在对象上就地定义了数组,我们将无法更改其内容。

// ?️ const Pages: {readonly home: '/', readonly menu: string[]}
export const Pages = {
  home: '/',
  menu: ['/about'],
} as const;

// ⛔️ Error: Property 'push' does not exist on type
// 'readonly ["/about"]'
Pages.menu.push('/test');

详细介绍 TypeScript 中的 'as const'