You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中`T extends infer P`里P的上下文含义解析

关于TypeScript类型工具KeysOfUnion<T>的疑问

我昨天遇到了这段TypeScript代码片段:

type KeysOfUnion<T> = T extends infer P ? keyof P : never
//                    ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ 

我对此感到困惑:这里到底在推断什么?我之前觉得infer关键字类似JS中的解构——虽然这个类比不完美,但帮我理解过很多场景。但我看不出T extends infer P的上下文:我在推断什么?P和T之间是什么关系?

我在TS Playground里测试了这段代码,原本猜测它可能用来区分有构造函数和没有构造函数的类型,测试结果如下:

type test1 = KeysOfUnion<{ name: "Bill"}> // name
type test2 = KeysOfUnion<"Orange"> // number | typeof Symbol.iterator | "toString" | "charAt" etc.
type test3 = KeysOfUnion<1> // "toString" | "valueOf" | "toFixed" etc.
type test4 = KeysOfUnion<true> // "valueOf"
type test5 =  KeysOfUnion<Object> // keyof Object

type test6  = KeysOfUnion<object> // never
type test7 = KeysOfUnion<{}> // never

object和{}的行为有点让人困惑,我推测这和TypeScript中object、{}与Object的区别有关。

type test8 = KeysOfUnion<undefined> // never
type test9 = KeysOfUnion<null> // never
type test10 = KeysOfUnion<never> // never
type test11 = KeysOfUnion<void> // never

不过测试结果可能更多和keyof P的逻辑相关——我还是搞不懂为什么要写T extends infer P,希望有人能解释清楚。

内容的提问来源于stack exchange,提问作者HynekS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:45:36