TypeScript const 和 const with as const

Guy*_*Guy 7 typescript typescript-generics

据我所知,TypeScript 将const string变量视为一个不可变的类型变量,只有该值而没有其他可能的值。我一直认为增加as const它是多余的。

为什么我在示例的第二部分得到以下内容?

“字符串”类型的参数不能分配给类型参数...

例子:

declare function each<T extends [any] | any[]>(cases: ReadonlyArray<T>): (name: string, fn: (...args: T) => any, timeout?: number) => void;

const foo1 = 'FOO' as const;
const bar1 = 'BAR' as const;

declare function action1(value: typeof foo1 | typeof bar1): void;

each([
  [foo1],
])('test name', (value) => {
  // okay
  action1(value);
});

const foo2 = 'FOO';
const bar2 = 'BAR';

declare function action2(value: typeof foo2 | typeof bar2): void;

each([
  [foo2],
])('test name', (value) => {
  // Argument of type 'string' is not assignable to parameter of type '"FOO" | "BAR"'.(2345)
  action2(value);
});
Run Code Online (Sandbox Code Playgroud)

上面的游乐场示例在这里。

Pan*_*kos 0

即使你的问题的第一部分(使用 as const )没有警告任何错误,它仍然不起作用,因为each方法没有编译为 javascript 代码,因此执行失败。

尽管您的示例试图解决 const 在缩小过程中的行为方式问题,但我认为它太复杂了。您可能会发现以下关于打字稿项目的建议问题很有用

支持Const类型约束