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

严格模式下如何获取TypeScript可选数组项的类型?

解决严格模式下获取可选数组项类型的报错问题

问题原因

ReportBody["rows"]的类型是{ name: string; id: number }[] | undefined,严格模式下TypeScript禁止对undefined类型执行索引操作(比如[0]),因此直接取[0]会抛出错误。

解决方案

方案1:使用NonNullable排除undefined

先通过NonNullable移除联合类型中的undefined,再获取数组元素类型:

type ReportBody = {
     rows?: Array<{
         name: string;
         id: number;
     }>
}
type ReportBodyRow = NonNullable<ReportBody["rows"]>[0];

方案2:用条件类型推断数组元素(通用方案)

定义一个工具类型,通过infer推断数组的元素类型,自动处理联合类型中的undefined:

type ReportBody = {
     rows?: Array<{
         name: string;
         id: number;
     }>
}
type ArrayElement<T> = T extends Array<infer U> ? U : never;
type ReportBodyRow = ArrayElement<ReportBody["rows"]>;

如果T是undefined,工具类型会返回never,但只要rows存在,就能正确获取元素类型。

方案3:使用Extract提取数组类型

从联合类型中提取出数组部分,再获取元素类型:

type ReportBody = {
     rows?: Array<{
         name: string;
         id: number;
     }>
}
type ReportBodyRow = Extract<ReportBody["rows"], Array<any>>[0];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:12:40