Edward Tanguay
Edward Tanguay

Reputation: 193322

How to understand syntax of this TypeScript/ES6 function?

I'm working through a tutorial on TypeScript/ES6.

The following code works e.g. outputs ["Richard Francis Burton"]:

let convertToStringArray: (v: string) => string[] = (value) => [value];

let name = "Richard Francis Burton";
let names = convertToStringArray(name);
console.log(names);

But how does one understand the TypeScript/ES6 syntax?

But this would be the same as the following function which doesn't work (Error TS1011: An element access expression should take an argument.)

function convertToStringArray(v: string) {
    return string[] = (value) => [value];
}

Upvotes: 1

Views: 80

Answers (2)

tkausl
tkausl

Reputation: 14279

this function returns string[] = (value) => [value];

No, the function returns string[] and the variable is initialized to (value) => [value];

         declaration           TypeScript type         (initial) value
/                      \  /                     \   /                \
let convertToStringArray: (v: string) => string[] = (value) => [value];

Upvotes: 3

Jared Smith
Jared Smith

Reputation: 21936

You've confused the inline type annotation with the function itself. What that says is you've got a variable convertStringToArray that has type (v: string) => string[] and is assigned (value) => [value]. It's equivalent to:

function convertToStringArray(value: string): string[] {
    return [value];
}

Playground

Upvotes: 1

Related Questions