tomision
tomision

Reputation: 994

How to add typescript type to ES6 arrow function?

Nowadays, I need to update javascript code to typescript.

But I found a question.

Before, I use a lot of arrow functions in before project. Now, I need to add type definition for many of them like after:

(a: number): string => { return `${a}` }

By using many npm packages, the package provide function type like after:

export declare type AAACallback = (a: number) => string

I wanna use the function type to my es6 arrow function.

Maybe you say like this:

let a: AAACallback = a => { return `${a}` }

// then use a

But I don't need to define a at all.

So, do you have any way to use function definition with es6 arrow function without define other variate?

Upvotes: 3

Views: 3767

Answers (1)

Matt McCutchen
Matt McCutchen

Reputation: 30879

TypeScript doesn't have a built-in syntax to annotate that an arrow function (or any other expression) has a given overall type without declaring a separate variable. (If you use a type assertion, you may be unintentionally downcasting the expression since type assertions allow both upcasts and downcasts.) One thing you can do is use an identity function:

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

element.addEventListener('click', id<AAACallback>(event => {}), false)

Upvotes: 2

Related Questions