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

如何在TypeScript中构建包含条件项的Map?

解决TypeScript中Map条件添加元素的类型错误问题

你遇到的错误是因为TypeScript无法自动推断filter(Boolean)过滤后的数组类型。原数组包含[string, Book]和null的联合类型,filter(Boolean)虽然在运行时会移除null,但TS的类型系统不会自动将其从数组类型中排除,导致Map构造函数收到不符合要求的类型。

下面是几种可行的解决方法:

方法一:使用类型断言

直接告诉TypeScript过滤后的数组是符合要求的类型:

type Book = {
  author: string,
  publishedDate: string,
}

const random = Math.random();

const booksMap = new Map<string, Book>([
  ['1', {
    author: 'Test',
    publishedDate: '2024-04-05'
  }],
  random > 0.5 ? ['1', {
    author: 'Test2',
    publishedDate: '2023-03-06'
  }] : null,
].filter(Boolean) as readonly [string, Book][])

方法二:自定义类型守卫函数

通过类型守卫让TS准确识别过滤后的有效元素:

type Book = {
  author: string,
  publishedDate: string,
}

const random = Math.random();

// 自定义类型守卫,判断元素是否为合法的Map条目
function isBookEntry(entry: unknown): entry is [string, Book] {
  return Array.isArray(entry) && 
         entry.length === 2 && 
         typeof entry[0] === 'string' && 
         typeof entry[1] === 'object' && 
         entry[1] !== null && 
         'author' in entry[1] && 
         'publishedDate' in entry[1];
}

const booksMap = new Map<string, Book>([
  ['1', {
    author: 'Test',
    publishedDate: '2024-04-05'
  }],
  random > 0.5 ? ['1', {
    author: 'Test2',
    publishedDate: '2023-03-06'
  }] : null,
].filter(isBookEntry))

方法三:先构建数组再条件添加

避免在数组字面量中混入null,直接通过条件语句添加元素:

type Book = {
  author: string,
  publishedDate: string,
}

const random = Math.random();

// 先初始化合法的条目数组
const bookEntries: [string, Book][] = [
  ['1', {
    author: 'Test',
    publishedDate: '2024-04-05'
  }]
];

// 满足条件时添加元素
if (random > 0.5) {
  bookEntries.push(['1', {
    author: 'Test2',
    publishedDate: '2023-03-06'
  }]);
}

const booksMap = new Map<string, Book>(bookEntries);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 04:35:09