据我所知,TypeScript认为const string变量是一个不可变的类型变量,只有该值,而没有其他可能的值。我一直认为在其中添加as const是多余的。
为什么我在这个例子的第二部分得到了下面的内容?
类型'string‘的参数不能分配给类型为.
示例:
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);
});发布于 2021-07-26 20:34:16
不要将const作为声明不可变变量的关键字(顺便说一句,在JS中也是如此)和as const (称为const断言 )混淆。
Const断言的行为因类型的不同而略有不同(参见附加的文档链接),但对于文字类型,它基本上意味着不能将其扩展(或扩展)到string。它将其缩小到特定的文字类型,该类型向编译器发出不接受string的信号,而这正是您所得到的准确错误。
发布于 2021-04-30 23:51:51
即使您的问题的第一部分(连同as const)没有警告任何错误,它仍然不能工作,因为each方法没有编译成javascript代码,因此执行失败。
虽然您的示例试图解决const在缩窄期间的行为问题,但我认为它太复杂了。您可能会发现以下有关打字本项目的建议问题是有用的
发布于 2021-05-01 10:34:58
TS能够推断出所有类型。(你应该付出一点爱))(只是添加额外的泛型来帮助TS找出所有的类型。TS是足够聪明的,即使没有as const,也能发现as const是常量。
declare function each<U extends string, V extends U[], T extends V>(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) => {
action1(value);
});
const foo2 = 'FOO';
const bar2 = 'BAR';
declare function action2(value: typeof foo2 | typeof bar2): void;
each([
[foo2],
])('test name', value => action2(value)); // ok正如你所看到的,我增加了额外的U和V仿制药。
请记住,如果你不能推断出某种类型,试着添加更多的泛型)) (这个规则在80%的时间内有效)
为什么我会得到“'string‘类型的参数不能分配给类型的参数.”在例子的第二部分?
这是因为value被推断为字符串。action2只期望foo或bar。因为string类型比foo | bar宽得多,所以TS抱怨
https://stackoverflow.com/questions/67340523
复制相似问题