24
loading...
This website collects cookies to deliver better user experience
:
symbol (colon symbol). After that, you can write an opening and closing bracket ()
. Within the brackets, you can write the parameter name followed by the :
(colon) symbol and then the type of the parameter. Following the braces, you should write an assignment operator followed by a greater than symbol (=>
) followed by the type of the value you want to be returned from the function call.(parameterName: parameterType) => returnType;
// a variable that accepts a function
// where it needs to have a parameter called name of type string
// and should return a value of type string
let sayGreeting: (name: string) => string;
// make a function which satisfies the
// `sayGreeting` function type expression
// Thus the below assignment of a function
// is allowed ✅.
sayGreeting = (name: string) => {
return `Hello ${name}`;
};
// call the function
const greeting = sayGreeting("John Doe");
// log the output
console.log(greeting); // Hello John Doe
function type expression
(aka type declaration for the entire function) where we need to have a parameter called name
with a type of string
and the function's return value should also be of string
type.function type expression
according to the above definition.// A simple function type expression
// where the function first parameter is name of type string
// and the return value should be of string type
(name: string) => string;
function type expression
is to enforce the parameter types and the return types and not the logic of the function.// a variable that accepts a function
// where it needs to have a parameter called name of type string
// and should return a value of type string
let sayGreeting: (name: string) => string;
sayGreeting
variable let's now make a function that accepts the structure of the function type expression we defined above.// a variable that accepts a function
// where it needs to have a parameter called name of type string
// and should return a value of type string
let sayGreeting: (name: string) => string;
// make a function which satisfies the
// `sayGreeting` function type expression
// Thus the below assignment of a function
// is allowed ✅.
sayGreeting = (name: string) => {
return `Hello ${name}`;
};
sayGreeting
function and pass the value of John Doe
as an argument to the function and see the output.// a variable that accepts a function
// where it needs to have a parameter called name of type string
// and should return a value of type string
let sayGreeting: (name: string) => string;
// make a function which satisfies the
// `sayGreeting` function type expression
// Thus the below assignment of a function
// is allowed ✅.
sayGreeting = (name: string) => {
return `Hello ${name}`;
};
// call the function
const greeting = sayGreeting("John Doe");
// log the output
console.log(greeting); // Hello John Doe