[英]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.