1

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
  • this function returns 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];
}
2
  • 2
    Not a TS expert, but I believe the (v: string) => string[] is the type (so a function which accepts a string, and returns an array of strings), whereas (value) => [value] is the function which is being assigned (which conforms to the type specified). Commented Jul 18, 2020 at 14:52
  • Isn't the string[] the return type? You can't return that, have you tried removing the string[] after the return statement? You can put that after the parameter definitions for the function convertToStringArray(v: string): string[] { Commented Jul 18, 2020 at 14:53

2 Answers 2

3

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

2 Comments

So that is the same as let convertToStringArray = (value: string): string[] => [value];, right?
Correct. Or just let convertToStringArray = (value: string) => [value];
1

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

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.