3

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?

7
  • Interesting you use the word “update” when referring to converting to typescript. Commented Oct 8, 2018 at 7:47
  • 1
    @evolutionxbox maybe I mean rewrite. you have any idea about my question? Commented Oct 8, 2018 at 7:48
  • @TomIsion not really clear to me what you are asking? You have a callback type AAACallback you assign an arrow function to it. What is the question ? You want to declare the type of a without the extra type ? Commented Oct 8, 2018 at 7:50
  • typescriptlang.org/docs/handbook/functions.html ? Commented Oct 8, 2018 at 7:53
  • @TitianCernicova-Dragomir AAACallback is typescript function type. I wanna use it to define my arrow function. Commented Oct 8, 2018 at 8:25

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.