TypeScript:从函数中返回_.orderBy,要使用什么返回类型?

加里

我安装的软件包是lodash@types/lodash

我有:

import _ from 'lodash';

function doSomething(): string[] {
  const letters = ['c', 'a', 'b'];

  return _.orderBy(letters, [null], ['asc']);
}

console.log(doSomething());

但是return _.orderBy(letters, [null], ['asc']);抛出错误:

Type '(string | number | (<U>(callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[]) | (() => string) | (() => string) | (() => string | undefined) | ((...items: string[]) => number) | ... 25 more ... | { ...; })[]' is not assignable to type 'string[]'.
  Type 'string | number | (<U>(callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[]) | (() => string) | (() => string) | (() => string | undefined) | ((...items: string[]) => number) | ... 25 more ... | { ...; }' is not assignable to type 'string'.
    Type 'number' is not assignable to type 'string'.

但显然,将返回字符串数组。

除了强制铸造到之外,还有什么方法可以解决此问题return _.orderBy(letters, [null], ['asc']) as string[];有没有一种方法可以指定orderBy要从其继承的类型letters

塞巴斯蒂安·克雷夫特(Sebastian Kreft)

您遇到的问题是因为[null]您传递给iteratees参数(第二个参数)的值与函数的签名不匹配。

iteratees参数被记录为type (Array[]|Function[]|Object[]|string[])

要修复您的呼叫,只需将第二个参数替换[_.identity]为默认值,或者将第二个参数设置为undefined,这也会触发使用默认值。在默认参数上签MDN文档

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在JavaScript中返回时为什么要使用括号?

在TypeScript中的异步函数中返回Promise

如何在TypeScript中声明函数的返回类型

函数的返回类型中{}的目的是什么?

在TypeScript中动态返回类构造函数

处理在Typescript中返回对象文字的函数

在TypeScript中返回类(=类构造函数)的工厂函数

什么时候需要在TypeScript中声明返回函数类型?

TypeScript推断类型构造函数中的回调返回类型

函数上缺少返回类型-在React(TypeScript)代码中

强制在Typescript中的类中返回所有函数的类型

Typescript函数,该函数从具有正确类型的数组中返回一项

为什么TypeScript无法检查函数的返回类型

Typescript:确保函数可以返回联合类型中的每个值

从异步函数销毁的对象中的类型在Typescript中返回

根据TypeScript中的参数在字典中定义函数的返回类型

如何声明从 Typescript 中启用 Typescript 的库中返回类型的函数

如何在 Typescript 中管理多个函数返回类型?

TypeScript 中泛型类型的返回构造函数

返回 AsyncFunction 的 Typescript 函数的适当返回类型是什么?

Typescript 函数返回类型中继

Typescript - 在具有条件返回类型的函数中返回特定类型

自动覆盖 TypeScript 子类中多个函数的返回类型

为什么 TypeScript 在推断函数的返回类型时不会自动使用文字类型?

如何在 TypeScript 中接受我的函数的通用返回类型?

TypeScript - 基于参数类型的函数返回类型

如果函数在 Python 中返回模块,要使用什么返回类型注释?

在 TypeScript 函数中输入返回的匿名类

为什么 TypeScript 不报告“错误”的函数返回类型