简体   繁体   English

记录中动态键的 TS 类型检查错误

[英]TS type-check error on dynamic key in record

Typescript throws an error Property 'forEach' does not exist on type 'string'. Typescript 引发错误Property 'forEach' does not exist on type 'string'. when explicitly checking if property is not a string using a variable key.当使用变量键显式检查属性是否不是字符串时。

let params: Record<string, string | string[]>;
const key = 'test';

// This works
if (params && typeof params['test'] !== 'string') {
  params['test'].forEach((element: string) => {});
}

// This fails
if (params && typeof params[key] !== 'string') {
  // FAILS with "Property 'forEach' does not exist on type 'string'."
  params[key].forEach((element: string) => {});
}

How should I type/check that a property is an array and forEach can run?我应该如何键入/检查一个属性是一个数组并且 forEach 可以运行?

Typescript compiler do not understood this patterns cause you can technically modify params[key] value anytime. Typescript 编译器不理解这种模式,因为您可以随时在技术上修改params[key]值。 So typeguard does not work in this case.所以 typeguard 在这种情况下不起作用。 At least that was the reason with older typescript version, maybe there is other way now.至少这是旧 typescript 版本的原因,也许现在还有其他方法。

To fix that you can assign params[key] to variable and then do the checks:要解决此问题,您可以将params[key]分配给变量,然后进行检查:

let params: Record<string, string | string[]> = {}
const key = 'test';


const value = params[key]
if (typeof value !== 'string') {
  value.forEach((element: string) => {});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何在 Typescript 中对这个 object 进行类型检查 - How do I type-check this object in Typescript 如何使用Flow类型执行写运行时类型检查表达式? - How can I do a write run-time type-check expression using Flow type? 为什么在使用function.apply时Closure不进行类型检查? - Why does not Closure type-check the parameters when using function.apply? 我是否应该(静态地)对第三方代码进行类型检查(例如使用Flow)? - Should I (statically) type-check Third-party codes (e.g. using Flow)? 如何使用 TypeScript 编译器 API 对使用 `require()` 导入的模块进行类型检查? - How to use the TypeScript Compiler API to type-check modules imported using `require()`? 如何使用动态密钥创建 TS 接口? - How create TS interface with dynamic key? 如何为 [key, val] 定义 TS 类型? - How to define TS type for [key, val]? 循环检查 object TS/JS 的类型 - Loop through and check type of object TS/JS 动态工厂方法-按字符串实例化类收到错误TS2322:类型“ Util”不能分配给类型“ void” - Dynamic Factory Method - Instantiate Class by String gets receives error TS2322: Type 'Util' is not assignable to type 'void' 错误ts2315类型&#39;observable&#39;不是通用的 - error ts2315 type 'observable' is not generic
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM