To add string
array type to function return value first, declare the function, then add a :
symbol (colon) after the parameters opening and closing brackets ()
and then type the word string
followed by []
symbol (opening and closing square brackets) to indicate that the function's return value is of string
array type.
TL;DR
// simple function with return
// value of string array type
function getGreetStrings(): string[] {
return ["Hey", "Hello", "Hi"];
}
For example, let's say we have a function called getGreetStrings()
and on calling the function should return an array containing only string values for example Hey
, Hello
, Hi
, etc.
It can be done like this,
// simple function
function getGreetStrings() {
return ["Hey", "Hello", "Hi"];
}
This is fine. But what if we need to enforce that the return value of the getGreetStrings
function should only return an array of strings and nothing else. To do that we can add the function return type like this,
// simple function with return
// value of string array type
function getGreetStrings(): string[] {
return ["Hey", "Hello", "Hi"]; // ✅ allowed
}
After defining the return type as a string
array, we must return an array of string values or it may show an error.
Now Let's also try to return a value other than the string
array type like this,
// simple function with return
// value not of string array type
function getGreetStrings(): string[] {
return [1, 2, 3]; // ❌ not allowed. Type 'number' is not assignable to type 'string'.
}
As you can see from the above code the TypeScript compiler is not allowing us to return the array and shows us an error saying Type 'number' is not assignable to type 'string'.
which is what we want to happen.
See the above codes live in codesandbox.
That's all 😃!