user677526
user677526

Reputation:

Typescript syntax: What the heck is this?

I'm a JS guy looking at an object in Typescript (it's being used in my work project) and I've stumbled into this syntax:

myClassFunction: () => void = () => {
    // my function internals here
}

I'm... honestly not sure what to make of this. What is this syntax, what does it do, what does it mean, and what is it called? (To my eyes, it looks as though we're assigning an anonymous function to another anonymous function, which shouldn't happen, but void is a TS type, so.....I'm stumped.)

Thanks!

Upvotes: 3

Views: 2668

Answers (1)

basarat
basarat

Reputation: 276393

There are two parts to that:

a type annotation:

: () => void

This means its a function that takes nothing and returns nothing

fat arrow function

() => {
    // my function internals here
}

This is an ES6 fat arrow function. More on these here : http://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

Opinion

Personally I wouldn't annotate this.

var myClassFunction = () => {
    // my function internals here
}

And just let typescript infer the type:

enter image description here

Upvotes: 3

Related Questions