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

TypeScript类型参数列表中的赋值语法解析

TypeScript泛型参数默认类型解析

你看到的extends Alice = Alice里的赋值,是给泛型参数T指定默认类型,具体规则如下:

  • 当使用Bob类型时,如果不主动传入泛型参数,TypeScript会自动将Alice作为T的类型。
  • 如果主动传入泛型参数,这个参数必须满足extends Alice的约束——也就是必须是Alice本身或者它的子类型。

举个实际例子更直观:

// 定义基础类型Alice
type Alice = { name: string };

// 带默认泛型参数的Bob类型
type Bob<T extends Alice = Alice> = T & { age: number };

// 1. 不传入泛型参数,T自动使用默认的Alice
const person1: Bob = { name: "Alice", age: 25 };
// 等价于 const person1: Bob<Alice> = { ... }

// 2. 传入符合约束的子类型
type AliceSubtype = Alice & { gender: string };
const person2: Bob<AliceSubtype> = { name: "Bob", age: 30, gender: "male" };

// 3. 传入不符合约束的类型会触发报错
// const person3: Bob<{ age: number }> = { age: 20 }; 
// 报错:类型"{ age: number; }"不满足约束"Alice",缺少name属性

简单来说,这个语法让泛型参数变为可选项,使用者未指定时用默认的Alice类型,同时保留了T必须继承自Alice的约束。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 09:32:01