Typescript Distributive Conditional Types

前端 未结 2 1616
旧巷少年郎
旧巷少年郎 2020-11-27 20:16

So i was going through the documentation on typescript and am not able to get my head around this concept.

So the documentation states :-

In instantiations

2条回答
  •  渐次进展
    2020-11-27 20:55

    Within a distributive conditional type (let's say type BoxIfObject = T extends object ? Array : T;) when the type is applied to a union (let's say number | { a : string }), it's as if the conditional type is applied to each constituent of the union and thus within the conditional type T will in turn refer to each constituent of the union (so T will first be number and then T will be { a : string })

    So when we apply BoxIfObject, T will never refer to the whole union number | { a : string } but to each of it's constituents in turn. Basically BoxIfObject = BoxIfObject | BoxIfObject<{ a : string }> = number | Array<{ a : string }

提交回复
热议问题