gpt4 book ai didi

TypeScript const 和 const with as const

转载 作者:行者123 更新时间:2023-12-04 11:32:36 29 4
gpt4 key购买 nike

据我所知,TypeScript 查看了 const string变量作为一个不可变的类型变量,只有那个值,没有其他可能的值。一直以为加as const那是多余的。
为什么我在示例的第二部分得到以下内容?

Argument of type 'string' is not assignable to parameter of type...


例子:
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);
});
Playground sample above is here.

最佳答案

不要混淆 constas const 作为声明不可变变量的关键字(顺便说一下,在 JS 中也是如此) ,它叫 const assertions .
Const 断言的行为根据类型略有不同(请参阅文档的附加链接),但在文字类型的情况下,它基本上意味着它不能扩展(或扩展)到 string .它将它缩小到特定的文字类型,这向编译器发出信号不接受 string这是您得到的确切错误。

关于TypeScript const 和 const with as const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67340523/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com