问题库 JavaScript / TypeScript how-to

TypeScript as const 有什么用

快速答案

as const 会把字面量收窄为只读常量类型。

js
const routes = ['home', 'about'] as const;
type Route = typeof routes[number];

使用要点

  • TypeScript 只在编译期提供保护,接口返回值仍要做运行时校验。
  • 类型收窄写清楚以后,再把数据交给业务函数,减少后续的断言。

相关内容