Reputation: 193322
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?
convertToStringArray
is the function name with a parameter name v
which has to be of type string
string[] = (value) => [value];
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
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
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];
}
Upvotes: 1