Let's look at some of the lesser used utility types in Typescript with examples
ThisType is a utility type that is used to set the type of the this
parameter in a function type, it effectively tells typescript what type the this
parameter should be.
Image a scenario where you have a type Person
defined in one of your dependencies
type Person = {
name: string;
age: number;
};
const person: Person = {
name: "John",
age: 30,
};
and you want to add a method to this object, you can use ThisType
to set the type of the this
parameter in the function type
const personMethods: ThisType<Person> & {
greet(): void;
} = {
greet() {
console.log(`Hi, my name is ${this.name} and I am ${this.age} years old`);
},
};
const personWithMethods = Object.assign(person, personMethods);
personWithMethods.greet();
Without ThisType
, typescript would not know what type the this
parameter should be, and you would get a type error.
// Below code will not work
const personMethods: {
greet(): void;
} = {
greet() {
console.log(`Hi, my name is ${this.name} and I am ${this.age} years old`);
},
};
const personWithMethods = Object.assign(person, personMethods);
personWithMethods.greet();
ThisType is a utility type that is used to set the type of the this
parameter in a function type, it effectively tells typescript what type the this
parameter should be.
ReturnType is a utility type that is used to extract the return type of a function type, it is a generic type that takes a function type as an argument and returns the return type of that function.
function add(a: number, b: number): number {
return a + b;
}
const result = ReturnType<typeof add>; // number
What if we have a function that returns a promise?
function fetchData(): Promise<string> {
return Promise.resolve("some data");
}
const result = ReturnType<typeof fetchData>; // Promise<string>
What if we just want the return type of the function without the Promise wrapper?
function fetchData(): Promise<string> {
return Promise.resolve("some data");
}
const result = Awaited<ReturnType<typeof fetchData>>; // string
its comes in handy when working with types which are not exported from a library or a function.