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

TypeScript中unknown extends T延迟类型用法及判定为false场景咨询

关于unknown extends CustomTypes[K]的解释与示例

核心逻辑

这个条件类型的作用是检测用户是否为CustomTypes中的指定键(ExtendableTypes范围内的键)自定义了具体类型:

  • 如果该键的类型仍是默认的unknown,则使用兜底类型B
  • 如果用户自定义了更具体的类型,则优先使用用户定义的类型

为什么unknown extends CustomTypes[K]能实现这个逻辑?

TypeScript中,X extends Y判断的是X是否是Y的子类型:

  • unknown是所有类型的父类型,只有当Y是unknown或any时,unknown才会是Y的子类型(即unknown extends unknown/unknown extends any为true)
  • 当Y是任何具体类型(比如接口、string、number等)时,unknown不是它的子类型,此时unknown extends Y为false

场景1:条件为true(默认情况)

当CustomTypes未被扩展时,所有键的类型都是默认的unknown,此时条件成立,返回兜底类型B:

// 未扩展CustomTypes,使用默认定义
type DefaultEditor = ExtendedType<'Editor', { id: string }>;
// 等价于:unknown extends unknown → true → DefaultEditor = { id: string }

type DefaultText = ExtendedType<'Text', { content: string }>;
// DefaultText = { content: string }

场景2:条件为false(用户自定义类型)

当你扩展CustomTypes,给某个键指定具体类型后,unknown extends CustomTypes[K]就会变为false,此时返回用户自定义的类型:

// 扩展CustomTypes,为Editor定义自定义类型
interface CustomTypes {
  Editor: {
    id: string;
    customFeature: boolean;
    createdAt: Date;
  };
  // Element和Text仍保持默认的unknown
}

// 此时ExtendedType会优先使用自定义的Editor类型
type CustomEditor = ExtendedType<'Editor', { id: string }>;
// 等价于:unknown extends { id: string; ... } → false → CustomEditor = { id: string; customFeature: boolean; createdAt: Date }

// Element未自定义,仍使用兜底类型
type CustomElement = ExtendedType<'Element', { tag: string }>;
// CustomElement = { tag: string }

补充:特殊情况——CustomTypes[K]为any

如果用户给键指定的类型是any,unknown extends any会返回true,此时仍会使用兜底类型B:

interface CustomTypes {
  Text: any;
}

type TextType = ExtendedType<'Text', { content: string }>;
// unknown extends any → true → TextType = { content: string }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 04:02:00