简体   繁体   English

打字稿泛型,未知的嵌套函数参数

[英]Typescript generics, unknown nested function param

i have som problem with generic function which has function with unknown param as param. 我有泛型函数的som问题,该函数具有将未知参数作为参数的函数。

export const inject = <I,V>(fn:<U>(input?:U) => V, resolveWithPayload: boolean, resolveArgs?: I) => <R>(payload:R):R => {
    resolveWithPayload ? fn(payload) : resolveArgs ? fn(resolveArgs) : fn();
    return  payload;
};

const fn = (value:number):number => {
    propertyToMutate = value;
    return propertyToMutate;
}

const res =_fish.inject(fn,false,60)(50);
but calling it ends with :

Argument of type '(value: number) => number' is not assignable to parameter of type '(input?: U) => number'. 类型((value:number)=> number'的参数不能分配给类型'(input ?: U)=> number'的参数。 Types of parameters 'value' and 'input' are incompatible. 参数“值”和“输入”的类型不兼容。 Type 'U' is not assignable to type 'number'. “ U”类型不可分配给“数字”类型。

if i change code this way: 如果我以这种方式更改代码:

export const inject = <I,V,U>(fn:(input?:U) => V, resolveWithPayload: boolean, resolveArgs?: I) => <R>(payload:R):R => {
    resolveWithPayload ? fn(payload) : resolveArgs ? fn(resolveArgs) : fn();
    return  payload;
};

it ends by type definition error in inject itself like: 它以注入自身的类型定义错误结束,如下所示:

TS2345: Argument of type 'R' is not assignable to parameter of type 'U'. TS2345:无法将类型“ R”的参数分配给类型“ U”的参数。

TS2345: Argument of type 'I' is not assignable to parameter of type 'U'. TS2345:无法将类型“ I”的参数分配给类型“ U”的参数。

So what can i do, if i dont know type of input of "fn" ? 那么,如果我不知道“ fn”的输入类型,该怎么办?

thanks 谢谢

The first error is caused because inject expects a function with signature <U>(input?: U) => V , but the one you provided has signature (value: number) => number . 发生第一个错误是因为inject需要具有签名<U>(input?: U) => V的函数,但是您提供的(value: number) => number具有签名(value: number) => number In other words, inject expects that fn is a generic function over the type U that accepts a parameter of type U | undefined 换言之, inject期望fn是在型通用函数U接受类型的参数U | undefined U | undefined , but the fn that you pass to it accepts a parameter of type number . U | undefined ,但是传递给它的fn接受类型为number的参数。

It's hard to know what exactly you're trying to accomplish with all of these generics, but perhaps you're looking for something like this: 很难知道您要使用所有这些泛型到底要完成什么,但是也许您正在寻找这样的东西:

export const inject = <U>(fn:(input?:U) => U, resolveWithPayload: boolean, resolveArgs?: U) => (payload:U):U => {
    resolveWithPayload ? fn(payload) : resolveArgs ? fn(resolveArgs) : fn();
    return payload;
};

const fn = (value:number = 0):number => {
    propertyToMutate = value;
    return propertyToMutate;
}

Notice that number is the only required type parameter 请注意, number是唯一必需的类型参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM