对不同类型的项目使用 _.flatten 时出现类型错误
Type error using _.flatten with items of different types
在我的 TypeScript 代码中,Lodash 的 _.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);
您必须在 flatten
上指定泛型类型参数,让 TS 知道值可以是 string
或 Item
:
const flattened = _.flatten<string | Item>([arr, item]);
在我的 TypeScript 代码中,Lodash 的 _.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);
您必须在 flatten
上指定泛型类型参数,让 TS 知道值可以是 string
或 Item
:
const flattened = _.flatten<string | Item>([arr, item]);