TypeScript:文字的“const myVar”和“const myVar as const”之间的区别
我的问题很简单,我想了解使用 as const
转换文字与泛型的推断之间的关系。
这里是一个示例重现:
declare global {
interface String {
// @ts-expect-error Simulate skipLibCheck
toUpperCase<T>(this: T): Uppercase<T>;
}
}
export {};
const strA = "mylowercasedstring"; // typed as "mylowercasedstring" (literal)
const strB = "mylowercasedstring" as const; // also typed as "mylowercasedstring" (literal)
const resultA = strA.toUpperCase(); // typed as string
const resultB = strB.toUpperCase(); // typed as "MYLOWERCASEDSTRING" (literal)
// why?
为什么 resultA
没有像 resultB
那样正确推断?
My question is pretty simple here, I would like to understand the the relationship between casting a literal with as const
and the infer of a generics.
Here a sample repro:
declare global {
interface String {
// @ts-expect-error Simulate skipLibCheck
toUpperCase<T>(this: T): Uppercase<T>;
}
}
export {};
const strA = "mylowercasedstring"; // typed as "mylowercasedstring" (literal)
const strB = "mylowercasedstring" as const; // also typed as "mylowercasedstring" (literal)
const resultA = strA.toUpperCase(); // typed as string
const resultB = strB.toUpperCase(); // typed as "MYLOWERCASEDSTRING" (literal)
// why?
Why resultA
is not properly infered like resultB
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论