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

TypeScript无法推断TESTS数组内Map类型 求类型定义及解释

完整解决方案代码

// 基础测试规则:所有断言共用的结构
type TestRule = {
  test: 'equal' | 'include' | 'notInclude';
  expected: string;
};

// 测试配置项的value类型:覆盖三种合法形态
type TestConfigValue = TestRule | Map<string, TestRule> | TestRule[];

// 直接给TESTS标注定义好的类型即可
const TESTS: [string, Map<string, TestConfigValue>][] = [
  ['reminderEmail', new Map([  
    ['subject', { test: 'equal', expected: 'Kindly complete your setup' }],
    ['headers', new Map([
      ['X-Link', { test: 'equal', expected: 'someUrl' }],
      ['X-Template-Name', { test: 'equal', expected: 'reminderFirst' }],
      ['X-Template-Version', { test: 'equal', expected: 'someVersion' }],
    ])],
    ['html', [
      { test: 'include', expected: "Here&#x27;s your reminder" },
      { test: 'include', expected: 'someUrl' },
      { test: 'include', expected: 'someUrl' },
      { test: 'include', expected: 'device' },
    ]],
    ['text', [
      { test: 'include', expected: "Here's your reminder" },
      { test: 'notInclude', expected: 'someUrl' },
      { test: 'notInclude', expected: 'someUrl' },
      { test: 'notInclude', expected: 'utm_source=email' },
    ]],
  ])],       
];

类型定义逻辑说明

  • 第一步先抽离最小复用单元TestRule:所有测试断言的结构完全一致,test字段只有三个合法取值,expected固定为字符串,定义后TS会自动校验这两个字段的格式,避免拼写错误。
  • 第二步定义配置项value的联合类型TestConfigValue:代码中第二层Map的value有三种合法格式:
    • 单个测试规则:比如subject对应的值
    • 嵌套Map:比如headers对应的值,key为请求头名称,value为单个测试规则
    • 测试规则数组:比如html、text对应的值,包含多个测试规则
      用联合类型可以完整覆盖这三种合法场景。
  • 第三步定义TESTS整体类型:TESTS是数组,每个元素是固定长度的元组,第一个元素为测试用例名称字符串,第二个元素为配置Map,所以直接标注为[string, Map<string, TestConfigValue>][]即可。

如果需要更严格的校验,还可以进一步收紧类型范围,比如限定测试用例名称、配置Map的key只能是'subject'|'headers'|'html'|'text'等预设值。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 18:12:02