简体   繁体   English

带有泛型的 Typescript 箭头函数的语法是什么?

[英]What is the syntax for Typescript arrow functions with generics?

The typescript handbook currently has nothing on arrow functions.打字稿手册目前没有关于箭头功能的内容。 Normal functions can be generically typed with this syntax: example:普通函数可以使用以下语法进行一般类型化:示例:

function identity<T>(arg: T): T {
    return arg;
}

What is the syntax for arrow functions?箭头函数的语法是什么?

The full example explaining the syntax referenced by Robin ... brought it home for me:解释Robin 引用的语法的完整示例……为我带回家:

Generic functions通用函数

Something like the following works fine:类似以下的工作正常:

function foo<T>(x: T): T { return x; }

However using an arrow generic function will not:但是,使用箭头通用函数不会:

const foo = <T>(x: T) => x; // ERROR : unclosed `T` tag

Workaround: Use extends on the generic parameter to hint the compiler that it's a generic, eg:解决方法:在泛型参数上使用扩展来提示编译器它是泛型的,例如:

const foo = <T extends unknown>(x: T) => x;

If you're in a .tsx file you cannot just write <T> , but this works:如果你在一个.tsx文件中,你不能只写<T> ,但这有效:

const foo = <T, >(x: T) => x;

As opposed to the extends {} hack, this hack at least preserves the intent.extends {} hack 不同,此 hack 至少保留了意图。

I found the example above confusing.我发现上面的例子令人困惑。 I am using React and JSX so I think it complicated the scenario.我正在使用 React 和 JSX,所以我认为它使场景复杂化。

I got clarification from TypeScript Deep Dive , which states for arrow generics:我从TypeScript Deep Dive得到了澄清,其中说明了箭头泛型:

Workaround: Use extends on the generic parameter to hint the compiler that it's a generic, this came from a simpler example that helped me.解决方法:在泛型参数上使用扩展来提示编译器它是泛型的,这来自一个对我有帮助的更简单的示例。

    const identity = < T extends {} >(arg: T): T => { return arg; }

The language specification says on p.64f语言规范在 p.64f 上说

A construct of the form < T > ( ... ) => { ... } could be parsed as an arrow function expression with a type parameter or a type assertion applied to an arrow function with no type parameter. < T > ( ... ) => { ... } 形式的构造可以解析为带有类型参数的箭头函数表达式或应用于没有类型参数的箭头函数的类型断言。 It is resolved as the former[..]它被解决为前者[..]

example:例子:

// helper function needed because Backbone-couchdb's sync does not return a jqxhr
let fetched = <
           R extends Backbone.Collection<any> >(c:R) => {
               return new Promise(function (fulfill, reject) {
                   c.fetch({reset: true, success: fulfill, error: reject})
               });
           };

This works for me这对我有用

const Generic = <T> (value: T) => {
    return value;
} 

so late, but with ES6 no need extends it still work for me.... :)这么晚了,但是使用 ES6 不需要扩展它仍然对我有用....:)

let getArray = <T>(items: T[]): T[] => {
    return new Array<T>().concat(items)
}

let myNumArr = getArray<number>([100, 200, 300]);
let myStrArr = getArray<string>(["Hello", "World"]);
myNumArr.push(1)
console.log(myNumArr)

while the popular answer with extends {} works and is better than extends any , it forces the T to be an object虽然extends {}的流行答案有效并且比extends any更好,但它强制T成为一个对象

const foo = <T extends {}>(x: T) => x;

to avoid this and preserve the type-safety, you can use extends unknown instead为避免这种情况并保持类型安全,您可以使用extends unknown

const foo = <T extends unknown>(x: T) => x;

This works for me这对我有用

 const logSomething = <T>(something:T): T => {
       return something;
    }

I to use this type of declaration:我使用这种类型的声明:

const identity: { <T>(arg: T): T } = (arg) => arg;

It allows defining additional props to your function if you ever need to and in some cases, it helps keeping the function body cleaner from the generic definition.如果您需要,它允许为您的函数定义额外的道具,并且在某些情况下,它有助于使函数体与通用定义保持清洁。

If you don't need the additional props (namespace sort of thing), it can be simplified to:如果你不需要额外的道具(命名空间之类的东西),它可以简化为:

const identity: <T>(arg: T) => T = (arg) => arg;

In 2021, Ts 4.3.3 2021年,Ts 4.3.3

const useRequest = <DataType, ErrorType>(url: string): Response<DataType, ErrorType> 
   => {
      ...
   }

I know I am late to this answer.我知道我迟到了这个答案。 But thought of answering this in case anyone else finds it helpful.但是考虑回答这个问题,以防其他人发现它有帮助。 None of the answers mention how to use generics with an async arrow function.没有一个答案提到如何使用具有async箭头函数的泛型。

Here it goes :它是这样的:

const example = async <T> (value: T) => {
    //awaiting for some Promise to resolve or reject;
     const result = await randomApi.getData(value);

} 

在此处输入图片说明

Using <T, extends {}> throws an error when you try to pass null as parameter.当您尝试将 null 作为参数传递时,使用 <T, extends {}> 会引发错误。 I will prefer using <T,> because it clears the issue.我更喜欢使用 <T,> 因为它可以解决问题。 I am yet to get the reason why.我还没有得到原因。 But this worked for me.但这对我有用。

在此处输入图片说明

Adding an example for multiple depended generic types:添加多个依赖泛型类型的示例:

This function, was converted to arrow function as the following:此函数被转换为箭头函数,如下所示:

http.get = function <T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R> {
            config.withCredentials = true;
            ....
          };

Notice the extends instead of the equal sign:注意扩展而不是等号:

http.get = async <T extends any, R extends unknown = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R> => {
            config.withCredentials = true;
            ...
          };

Here I got 2 cases of arrow function with generics:在这里,我得到了 2 例带有泛型的箭头函数:

  • To call directly:直接调用:
const foo = <T>(value: T): void => {
    console.log(value);
foo('hello') // hello
}
  • To create a type to use later:要创建稍后使用的类型:
type TFoo<S> = (value: S) => boolean;
const foo: TFoo<number> = (value) => value>0;
console.log(foo(1)) // true
console.log(foo(-1)) // false

Hopefully this helps somewhere!希望这在某个地方有所帮助!

The typescript handbook currently has nothing on arrow functions.打字手册目前没有关于箭头的功能。 Normal functions can be generically typed with this syntax: example:普通函数可以使用以下语法进行通用键入:示例:

function identity<T>(arg: T): T {
    return arg;
}

What is the syntax for arrow functions?箭头功能的语法是什么?

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

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