TypeScript:文字的“const myVar”和“const myVar as const”之间的区别

发布于 2025-01-09 09:32:24 字数 649 浏览 6 评论 0原文

我的问题很简单,我想了解使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文