18
loading...
This website collects cookies to deliver better user experience
type alias
and write the function signature (aka function call signature) and the property with its type you need to attach to the function inside the type alias
.// type alias for `verifyAge` function
// with function signature and a property with its type
type VerifyAgeFunc = {
(age: number): boolean;
usedBy: string;
};
// the function itself that
// satisfies the above type alias
let verifyAge = <VerifyAgeFunc>((age: number) => (age > 18 ? true : false));
// add a property called `usedBy`
verifyAge.usedBy = "Admin"; // allowed ✅.
verifyAge
which needs to have a parameter called age
with type number
, and the return value of the function should be of type boolean
. Adding type to a function can be done by defining a function type expression
.// function type expression for verifyAge function
let verifyAge: (age: number) => boolean;
function type expression
, let's try to add a property called usedBy
and try to set its value to a string of Admin
.// function type expression for verifyAge function
let verifyAge: (age: number) => boolean;
// the function itself that satisfies
// the above function type expression
verifyAge = (age: number) => (age > 18 ? true : false);
// try to add a property called `usedBy`
verifyAge.usedBy = "Admin"; // not allowed ❌. Property 'usedBy' does not exist on type '(age: number) => boolean'.
verifyAge
function and shows an error saying Property 'usedBy' does not exist on type '(age: number) => boolean'.
.type alias
and define the function signature as well as the property with its type we need to use inside the type alias
.VerifyAgeFunc
like this,// type alias for `verifyAge` function
type VerifyAgeFunc = {
// cool code here
};
function signature
as well as the property with its type separated by the ;
symbol (semi-colon).// type alias for `verifyAge` function
// with function signature and a property with its type
type VerifyAgeFunc = {
(age: number): boolean;
usedBy: string;
};
=>
symbol (assignment with greater than symbol) combination after that parameter list brackets as we do it for function type expression
.VerifyAgeFunc
type alias, we can now use it as the type for the verifyAge
function variable by casting the entire function using the <>
symbol (angle brackets) and then writing the VerifyAgeFunc
inside the brackets.// type alias for `verifyAge` function
// with function signature and a property with its type
type VerifyAgeFunc = {
(age: number): boolean;
usedBy: string;
};
// the function itself that
// satisfies the above type alias
let verifyAge = <VerifyAgeFunc>((age: number) => (age > 18 ? true : false));
// add a property called `usedBy`
verifyAge.usedBy = "Admin"; // allowed ✅.
usedBy
is now allowed by the TypeScript compiler since we have defined it in the VerifyAgeFunc
type alias. Yay! 🥳.