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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…