Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

javascript - What does syntax in example code mean (typescript, react)?

const example: (string: string) => string = string => {
  return string.split("");
}

Its not a detailed question - I know, but I couldnt think of another way to ask and I simply do not understand what is happening in the below code. I only understand only string as type is accepted, but how is this even a function -shouldnt it be:

const example = (string:string) => return string.split("")}

instead ? Thanks!!

UPDATE: There was some miscommunication maybe. I only want to understand the following (in bold letters):

const example**: (string: string) => string** = string => {
  return string.split("");
}
  1. why is it ":" and not "="?
  2. what is: => string = string => why not just = string => ?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Okay, actually there's a type error, it should be:

const example: (string: string) => string[] = string => {
  return string.split("");
}

instead of (string: string) => string because string.split() will return an array.

also, it's better to rename the argument to something other than string as it can be easily confused with the type string.

Here's a fixed version:

const example: (someArg: string) => string[] = (someString) => {
  return someString.split('');
};

So, the function "example" simply takes an argument(of type string) and returns an array of strings that is indicated by (string: string) => string[].

You can also use the below syntax if you find above a bit confusing:

const example2 = (someString: string): string[] => {
    return someString.split('');
};

Update:

Considering this (string: string) => string,

why is it ":" and not "="?

It is not = because we're not yet assigning the value we're still in the process of assigning the type, after giving the type we're indeed using = to finally give it a value(which is an arrow function)

what is: => string = string => why not just = string => ?

typescript does understand that the returned value is an array of strings but just to explicitly mention the return type(if in case typescript fails to automatically infer), we use => to separate the argument types and return type. Think of this like an arrow function equivalent to assigning types to a function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...