类型断言通过 as 告诉编译器"相信我,这个值是 X 类型"。它不进行任何运行时转换或检查 — 它只改变编译器对该值的处理方式。
ts
const el = document.() ;
el. = ;
data = .(str) ;
类型断言通过 as 告诉编译器"相信我,这个值是 X 类型"。它不进行任何运行时转换或检查 — 它只改变编译器对该值的处理方式。
const el = document.() ;
el. = ;
data = .(str) ;
断言会推翻编译器的判断 — 如果你错了,你会得到运行时崩溃,没有警告:
const x = "hello" as unknown as number; // double assertion — compiler stops complaining
x.toFixed(2); // 💥 runtime error: x.toFixed is not a function
断言不会使该值成为该类型;它只是使检查器沉默。你已经从编译器中剥夺了正确性的责任。
// 1. type guard — actually verify at runtime
if (typeof input === "string") { /* input is string, proven */ }
// 2. validation library (zod) for external data
const user = UserSchema.parse(data); // throws if shape is wrong
as const 是不同的const point = { x: 1 } as const; // not a risky cast — narrows to literal/readonly
断言有时是必要的(DOM API、缩小你已经检查过的 unknown),但每一个都是编译器无法保护你的地方。
对不受信任的数据优先使用类型守卫或模式验证,并将每个 as 视为一个小的、有意的"我知道得更好",你必须确保它是正确的。