类型 'string | 中不存在属性 'forEach'细绳[]'

时间:2021-03-03 02:38:39

标签: typescript type-conversion

我有这个代码

  @Where(
    ['owner', 'Manager', 'Email', 'productEmail', 'Region'],
    (keys: string[], values: unknown) => {
      const query = {};

      keys.forEach((k: string) => {            
    }
  )

当我为类型检查启用严格规则时,它在抱怨

Argument of type '(keys: string[], values: unknown) => {}' is not assignable to parameter of type '(key: string | string[], values: unknown) => unknown'.
  Types of parameters 'keys' and 'key' are incompatible.
    Type 'string | string[]' is not assignable to type 'string[]'.
      Type 'string' is not assignable to type 'string[]'.ts

当我将键类型更改为 (keys: string | string[], values: unknown) =>

我收到另一个错误

Property 'forEach' does not exist on type 'string | string[]'.
  Property 'forEach' does not exist on type 'string'.ts 

有人知道如何解决这个问题吗。

1 个答案:

答案 0 :(得分:2)

问题在于 Typescript 试图避免您在类型为 forEach 时在 keys 上意外调用 string,因为它没有 forEach 属性并且会在运行时失败。 @Where 装饰器是您实现的吗?还是来自第三方软件包?

如果您需要在调用 string | string[] 的同时保留类型 forEach,则需要在调用该方法之前确保 keys 是一个数组,如下所示。

if (Array.isArray(keys)) {
    keys.forEach(...);
}