String type annotations can be added to function parameters by declaring the function and then adding the name of the parameter followed by the :
symbol (colon) and then the type string
after the symbol.
TL;DR
// add string type annotation
// to the parameter name
function greetPerson(name: string) {
return `Hello ${name}`;
}
// call the function
greetPerson("John Doe"); // ✅ allowed
For example, let's say we have a function called greetPerson
and on calling the function greets the person with the string Hello
with the name of the person.
So to get the name of the person we can use a parameter called name
. It can be done like this,
// a simple function
function greetPerson(name) {
return `Hello ${name}`;
}
Now we need to only allow string
type values as the value for the parameter name
. To do that we can add a string
type annotation to the function parameter. In our case, the parameter is name
.
It can be done like this,
// add string type annotation to
// the parameter name
function greetPerson(name: string) {
return `Hello ${name}`;
}
Now let's try to call the function greetPerson
and then pass a string value as an argument to the function like this,
// add string type annotation
// to the parameter name
function greetPerson(name: string) {
return `Hello ${name}`;
}
// call the function
greetPerson("John Doe"); // ✅ allowed
As you can see from the above code TypeScript allowed us to pass the string value of John Doe
to the function parameter name
since the allowed type for the name
function parameter is a string
.
Now let's try to pass another value of number
type 1
to the name
function parameter to see what happens,
// add string type annotation
// to the parameter name
function greetPerson(name: string) {
return `Hello ${name}`;
}
// call the function
greetPerson("John Doe"); // ✅ allowed
greetPerson(1); // ❌ not allowed. Argument of type 'number' is not assignable to parameter of type 'string'.
As you can see that the TypeScript will throw an error saying that the Argument of type 'number' is not assignable to parameter of type 'string'.
which is also what we want to happen.
See the above codes live in codesandbox.
That's all 😃!