Dan*_*Dan 12 javascript functional-programming typescript lodash
我一直在关注有关Lodash的文章,“ 为什么使用_.chain是一个错误”,它着重指出您可以使用来消除对链条的需求Flow。
给出的示例是以下使用链
import _ from "lodash";
_.chain([1, 2, 3])
.map(x => [x, x*2])
.flatten()
.sort()
.value();
Run Code Online (Sandbox Code Playgroud)
可以使用流程转换为以下内容
import map from "lodash/fp/map";
import flatten from "lodash/fp/flatten";
import sortBy from "lodash/fp/sortBy";
import flow from "lodash/fp/flow";
flow(
map(x => [x, x*2]),
flatten,
sortBy(x => x)
)([1,2,3]);
Run Code Online (Sandbox Code Playgroud)
但是,当我使用TypeScript实现此功能时,出现以下错误
对象的类型为'unknown'.ts(2571)
有什么方法可以解决此问题,以便TypeScript知道它正在处理哪种类型?
在解释JavaScript / TypeScript时(注意:将TypeScript代码转换为JavaScript,然后再对其进行解释),当您使用链时,打字稿会首先知道其处理的类型(即数字数组)。但是,对于流,流函数要作用的类型是最后指定的,因此它不知道它将使用什么类型,因此需要泛型或另一种指示将要使用的类型的方法。另外,生成此错误的linter也在解释代码,因此当使用“ flow”时,当输入最后出现时,它不知道要处理的类型。
当您将lodash与TypeScript结合使用时,您所使用的函数将支持泛型来指定它们要处理的类型。
因此,您可以按以下说明从lodash函数输入/输出的内容:
flow(
map<number, [number, number]>(x => [x, x * 2]),
flatten,
sortBy(x => x)
)([1, 2, 3]);
Run Code Online (Sandbox Code Playgroud)
或如dareka建议的那样:
flow(
map((x: number) => [x, x * 2]),
flatten,
sortBy(x => x)
)([1, 2, 3])
Run Code Online (Sandbox Code Playgroud)
但这又只能奏效,因为我们正在向编译器指示将要作用的类型。
这些代码片段的工作示例可以在此处找到。
请注意,如何明确定义函数的输入/输出,例如,“ map”表示要迭代的类型是数字,而运算的结果是元组。
小智 5
我喜欢本·史密斯(Ben Smith)的回答,因为这对我来说很有教育意义。但是我要建议这个
map((x: number) => [x, x*2])
Run Code Online (Sandbox Code Playgroud)
甚至
map((x: any) => [x, x*2])
Run Code Online (Sandbox Code Playgroud)
对于更一般的情况。如果您不想太严格,它似乎可以正常工作,并且会得到尽可能多的推断。
该_.flow()方法生成无点功能。这样可以防止打字稿推断输入的类型。
要解决此问题,请将函数分配给变量,然后添加函数的类型。声明函数参数和输出后,typescript可以推断流内部函数的内部类型。
将函数分配给变量后,可以调用它(sandobx):
const fn: (numbers: number[]) => number[] = flow(
map(x => [x, x*2]),
flatten,
sortBy(x => x)
);
const result = fn([1,2,3]);
Run Code Online (Sandbox Code Playgroud)
或者,如果您想立即调用该函数,请使用类型断言(sandbox):
type Fn = (numbers: number[]) => number[];
const result = (flow(
map(x => [x, x * 2]),
flatten,
sortBy(x => x)
) as Fn)([1, 2, 3]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1937 次 |
| 最近记录: |