我发现
type B = {
foo: string;
bar: number;
};
function get<F extends B, K extends keyof B>(f: F, k: K): F[K] {
return f[k];
}
直觉上等同于
function get<F extends B, K extends keyof B>(f: F, k: K): F extends B ? F[K] : undefined {
return f[k];
}
但后者不进行类型检查:
Type 'F[K]' is not assignable to type 'F extends B ? F[K] : undefined'.
Type 'F["foo"] | F["bar"]' is not assignable to type 'F extends B ? F[K] : undefined'.
Type 'F["foo"]' is not assignable to type 'F extends B ? F[K] : undefined'.
Type 'string' is not assignable to type 'F extends B ? F[K] : undefined'.
因此有一个问题:TS 编译器对我不明显的类型了解多少?
最佳答案
这更像是你知道的比它知道的更多......编译器不会尝试对依赖于未解析泛型类型参数的条件类型进行任何深入分析。也就是说,条件类型 F extends B ? F[K] : undefined
并没有真正在函数实现内部进行评估,其中 F
尚未指定具体类型。所以虽然您很容易看到 F extends B ? F[K] : undefined
必须与 F[K]
相同,因为条件 F extends B
与通用约束 相同F extends B
,编译器甚至没有开始这样做(可能是出于性能原因)。
关于typescript - 为什么在这种情况下返回的总是真条件类型不进行类型检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57067022/