简体   繁体   English

Typescript:将function的参数类型定义为function和Z56B97998B338B9F37776

[英]Typescript: define the type of a parameter of a function as a function with generics

I have created a compose function like this我已经像这样创建了一个compose function

const composeTyped = <T, U, R>(f: (x: T) => U, g: (y: U) => R) => (x: T) => g(f(x));

It seems to me that both f and g are functions of type fGeneric which is defined as在我看来, fg都是fGeneric类型的函数,定义为

type fGeneric = <T, R>(arg: T) => R;

My problem is that I do not understand if and how I could use the type fGeneric to specify the type of f and g in composedType .我的问题是我不明白是否以及如何使用类型fGeneric来指定fg中的类型composedType To be more clear, if I do like this更清楚地说,如果我喜欢这样

const composeTyped_ = <T, U, R>(f: fGeneric, g: fGeneric) => (x: T) => g(f(x));

the function composeTyped_ is assigned the type (x: T) => unknown . function composeTyped_被分配类型(x: T) => unknown What I would like to obtain though is the type (x: T) => R .我想获得的是类型(x: T) => R

You need to define fGeneric so that it accepts generic type arguments:您需要定义fGeneric以便它接受泛型类型 arguments:

type fGeneric<T, R> = (arg: T) => R;

Then you can defined composeTyped_ like so:然后你可以像这样定义composeTyped_

const composeTyped_ = <T, U, R>(
  f: fGeneric<T, U>,
  g: fGeneric<U, R>
) => (x: T) => g(f(x));

This should now work nicely:现在应该可以很好地工作:

declare const f: (str: string) => number

declare const g: (num: number) => null

composeTyped_(f, g)

// Argument of type '(num: number) => null' is not assignable to parameter of type 
//   'fGeneric<number, string>'.
//  Type 'null' is not assignable to type 'string'.
composeTyped_(g, f) 

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

相关问题 在TypeScript中,泛型参数位于函数之前 - In TypeScript, generics parameter before function 带有泛型的 TypeScript 接口函数类型 - TypeScript Interface function type with generics 在 TypeScript 中使用一个参数来定义同一个函数中另一个参数的类型 - Using a parameter to define the type of another parameter in the same function in TypeScript 是否可以在 TypeScript 中使用一个没有“任何”的参数来定义代表 function 的类型? - Is it possible to define a type representing a function with one parameter without 'any' in TypeScript? 如何在TypeScript中为方法重载定义函数指针参数类型 - How to Define Function Pointer Parameter Type for Method Overload in TypeScript 根据 TypeScript 中的参数在字典中定义 function 的返回类型 - Define return type of a function in dictionary based on its parameter in TypeScript 我可以将 Typescript function 参数定义为具有 boolean 类型或字符串吗? - Can I define a Typescript function parameter to have a type of boolean or string? 为没有或许多不同参数类型的 function 定义 Typescript 类型 - Define a Typescript type for a function with none or many different parameter types unionType 不能为 generics Function Typescript 中的参数 - unionType cannot be generics Function Parameter in Typescript TypeScript generics 和 function 参数条件类型 - TypeScript generics and function parameter conditional types
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM