简体   繁体   English

为什么infer从函数的交集中选择最后一个function的类型呢?

[英]Why does infer choose the type from the last function from the intersection of functions?

type T = (() => 1) & (() => 2) extends () => infer R ? R : unknown
  1. Why is T not never ( 1 & 2 )?为什么T不是never1 & 2 )?
  2. Is the type always taken from the last function or from one of them?类型总是取自最后一个 function 还是其中一个?

infer will always take the last overload when faced with an intersection (which is really just another way to describe overloads), no matter how you define it. infer在遇到交集时总是采用最后一个重载(这实际上只是描述重载的另一种方式),无论您如何定义它。 The last overload is the last member in the intersection or last definition in the code:最后一个重载是交集中的最后一个成员或代码中的最后一个定义:

type One = (() => 1) & (() => 2);
type Two = { (): 1; (): 2; };

type MutuallyAssignable = One extends Two ? Two extends One ? true : false : false;
//   ^? true

function three(): 1;
function three(): 2;
function three() { return 42 }

type Three = typeof three;

class C {
    four(): 1;
    four(): 2;
    four() { return 42 }
}

type Four = C["four"];

type T<F> = F extends (...args: any[]) => infer R ? R : unknown;

type T01 = T<One>;
//   ^? 2
type T02 = T<Two>;
//   ^? 2
type T03 = T<Three>;
//   ^? 2
type T04 = T<Four>;
//   ^? 2

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM