[英]Typescript. Function typing
Hello I am learning typescript and i follow this exercises: Link您好,我正在学习 typescript,我遵循以下练习: 链接
I have problem understanding how should i proced with this example.我很难理解我应该如何处理这个例子。
there is a code like this:有这样的代码:
export function map(mapper, input) {
if (arguments.length === 0) {
return map;
}
if (arguments.length === 1) {
return function subFunction(subInput) {
if (arguments.length === 0) {
return subFunction;
}
return subInput.map(mapper);
};
}
return input.map(mapper);
}
and I am supposed to add types to this.我应该为此添加类型。 I managed to create something like this:
我设法创造了这样的东西:
export function map<T>(mapper: Function, input : T[]| any) : T[] | Function {
if (arguments.length === 0) {
return map;
}
if (arguments.length === 1) {
return function subFunction(subInput: T[]|any): T[] | Function {
if (arguments.length === 0) {
return subFunction;
}
return subInput.map(mapper);
};
}
return input.map(mapper);
}
typescript do not returns compilation errors now but i still fail the test. typescript 现在不返回编译错误,但我仍然没有通过测试。 I do not understand what it is expected from me to make this work.
我不明白我对完成这项工作的期望是什么。
I can check suggested answer but whe i look at it this is dark magic for me.我可以检查建议的答案,但是当我看到它时,这对我来说是黑魔法。
I could check test.ts
for what is expected but notation like const mapResult1 = map()(String)()([1, 2, 3]);
我可以检查
test.ts
的预期内容,但像const mapResult1 = map()(String)()([1, 2, 3]);
这样的符号is looking very strange for me.对我来说看起来很奇怪。
Well it's just some use case of the map
function:好吧,这只是
map
function 的一些用例:
map()
the result is map
itselfmap()
结果是map
本身map(String)
which returns subFunction
subFunction
的map(String)
subFunction()
which returns subFunction
itselfsubFunction
本身的subFunction()
subFunction([1, 2, 3])
which returns the result of the expression [1, 2, 3].map(String)
: ['1', '2', '3']
subFunction([1, 2, 3])
,它返回表达式[1, 2, 3].map(String)
的结果: ['1', '2', '3']
The type of this result is a string[]
because every element of the final array is the result of String
being called as a function is always a string
.此结果的类型是
string[]
因为最终数组的每个元素都是String
被称为 function 的结果始终是string
。 Your typings are supposed to resolve this type without even executing the code.您的打字应该在不执行代码的情况下解决这种类型。
Here is a simple solution:这是一个简单的解决方案:
interface SubFunction<I, O> {
(): SubFunction<I, O>;
(input: I[]): O[];
}
function map<I, O>(): typeof map;
function map<I, O>(mapper: (i: I) => O): SubFunction<I, O>;
function map<I, O>(mapper: (i: I) => O, input: I[]): O[];
function map<I, O>(mapper?: (i: I) => O, input?: I[]) {
if (mapper && input) {
return input.map(mapper);
}
if (mapper) {
const subFunction = (input?: I[]) => input ? input.map(mapper) : subFunction;
return subFunction;
}
return map;
}
const mapResult1 = map()(String)()([1, 2, 3]);
function
apart from top-level, no arguments
)function
除了顶级,没有arguments
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.