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

TypeScript中高效校验对象多值类型的方案(TS2322错误)

TypeScript严格类型检查的循环判断优化问题

我在TypeScript中实现严格类型检查时,采用逐个判断typeof的写法,IDE(IntelliJ)能正确验证变量为字符串,且无编译错误:

if (typeof file.key.stringValue !== 'string' ||
    typeof file.publishDate.stringValue !== 'string' ||
    typeof file.size.stringValue !== 'string' ||
    typeof file.url.stringValue !== 'string') {
        throw new Error('missing required values')
}

但这种方式不够高效,我尝试改用循环遍历指定key的写法:

for (const key of ['key', 'publishDate', 'size', 'url']) {
  if (typeof file[key].stringValue !== 'string') {
    throw new Error('missing required values')  
  }
}

此时IDE持续报错,编译器提示TS2322:Type 'string | undefined' is not assignable to type 'string',表示变量可能为undefined。即使将key声明为(keyof typeof file)[]类型,问题仍未解决。

后续我尝试了两种方案:一是使用类型谓词结合类型断言,二是使用非空断言并临时禁用eslint规则,最终选择了后者,但希望得到其他优化建议。

最终要构造的对象如下:

const clientFile: ClientFile = {
    key: file.key.stringValue,
    publishDate: file.publishDate.stringValue,
    size: parseInt(file.size.stringValue, 0),
    url: file.url.stringValue
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 14:06:18