Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 为什么在这种情况下,返回的总是true条件类型不进行类型检查_Typescript - Fatal编程技术网

Typescript 为什么在这种情况下,返回的总是true条件类型不进行类型检查

Typescript 为什么在这种情况下,返回的总是true条件类型不进行类型检查,typescript,Typescript,我发现 type B={ foo:string; 条:数字; }; 函数get(f:f,k:k):f[k]{ 返回f[k]; } 直觉上与相同 函数get(f:f,k:k):f扩展了B?F[K]:未定义{ 返回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 t

我发现

type B={
foo:string;
条:数字;
};
函数get(f:f,k:k):f[k]{
返回f[k];
}
直觉上与相同

函数get(f:f,k:k):f扩展了B?F[K]:未定义{ 返回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扩展了B?F[K]:未定义的
没有在函数实现中真正进行评估,其中F还没有指定具体类型。所以当你很容易看到
F扩展了B?F[K]:未定义的
必须与F[K]相同,因为条件F extends B与泛型约束F extends B相同,编译器甚至没有开始这样做(可能是出于性能原因)