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

TypeScript中如何扩展类型添加额外成员?解决赋值报错问题

TypeScript类型扩展实现方案

你当前的写法IntervalType[] & "year"逻辑错误,这是把数组类型和字符串类型做交叉,完全不符合扩展类型的需求,所以会出现**"Type 'year' is not assignable to type"(类型"year"无法赋值给目标类型)**的错误。

以下是两种正确的实现方式:

方式一:先扩展类型,再定义数组

// 原类型
declare type IntervalType = "day" | "week" | "month";

// 扩展原类型,加入新的"year"选项
type ExtendedIntervalType = IntervalType | "year";

// 定义包含扩展后类型元素的数组
const intervalTypes: ExtendedIntervalType[] = ["day", "month", "year"];

方式二:直接在数组类型中组合原类型与新值

如果不需要单独定义扩展后的类型,可以直接在数组的类型注解里组合原类型和新的字符串字面量:

declare type IntervalType = "day" | "week" | "month";

const intervalTypes: (IntervalType | "year")[] = ["day", "month", "year"];

这两种方式都是通过联合类型实现扩展,让数组既可以包含原IntervalType的所有值,也能容纳新增的"year"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 15:08:16