Ошибка ввода с использованием _.flatten с элементами разных типов - PullRequest
0 голосов
/ 19 октября 2019

В моем коде TypeScript у меня есть ошибка для функции _.flatten Лодаша. Код все еще работает, но TS выдает ошибку. Ошибка может быть найдена ниже, в комментариях к коду.

Как я могу решить эту проблему?

import _ from 'lodash';

interface Item {
  text: string;
}

const item: Item = {
  text: 'string',
};

const arr = ['a'];

/**

Argument of type '(Item | string[])[]' is not assignable to parameter of type 'ArrayLike<Many<string>>'.
  Index signatures are incompatible.
    Type 'Item | string[]' is not assignable to type 'Many<string>'.
      Type 'Item' is not assignable to type 'Many<string>'.
        Type 'Item' is missing the following properties from type 'readonly string[]': length, concat, join, slice, and 18 more.

 */
const flattened = _.flatten([arr, item]);

console.log(flattened);

1 Ответ

0 голосов
/ 19 октября 2019

Необходимо указать параметр универсального типа в flatten, чтобы TS знал, что значения могут быть string или Item:

const flattened = _.flatten<string | Item>([arr, item]);
...