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

TypeScript:如何在特定场景下正确使用extends关键字

问题解决方法

首先明确:extends关键字仅用于定义接口或类型的继承关系,不能直接在变量的类型注解里这么写,这就是你触发'?' expected错误的原因。

要让myPeeps数组的元素同时满足Person和Department两个接口的要求,有两种实用方案:

方案一:直接使用类型交集(&)

无需额外定义新接口,直接在变量类型里指定数组元素为两个接口的交集类型:

const myPeeps: (Person & Department)[] = [
    {name: 'A', active: true, id: 1, company:'', department: ''},
    {name: 'C', active: true, id: 2, company:'', department: ''},
    {name: 'D', active: true, id: 3, company:'', department: ''},
    {name: 'K', active: true, id: 4, company:'', department: ''},
    {name: 'T', active: true, id: 5, location: 'cali', company:'', department: ''}
]

Person & Department表示同时包含两个接口所有属性的类型,后缀[]代表该类型的数组。

方案二:定义继承式新接口(适合复用场景)

如果后续还有其他地方需要用到这个组合类型,可以先定义一个新接口,同时继承Person和Department,再用这个新接口作为数组类型:

// 定义新接口,继承两个原有接口
interface PersonWithDepartment extends Person, Department {}

const myPeeps: PersonWithDepartment[] = [
    // 数组内容同上
]

不存在“仅在特定场景下使用extends”的用法——extends是用来构建新类型的语法,不是直接给变量做类型标注的语法。如果只是myPeeps这一个变量需要组合类型,方案一更高效;如果需要复用组合类型,方案二更合适。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:35:35