The ReturnType
in TypeScript is a utility sort which is sort of much like the Parameters Type. It let’s you’re taking the return output of a perform, and assemble a sort based mostly off it.
The ReturnType Utility Kind
The ReturnType
utility sort may be very helpful in conditions the place the output of a particular perform must be taken in by one other perform. In that state of affairs, you would possibly create a brand new, customized sort, that the output of a perform constrains itself to.
Let us take a look at a foolish instance to place it into context. Under, we outline a brand new sort, which has two properties, a
, and b
, each of that are numbers. A perform then turns all numbers on this object into strings, and returns a brand new sort. We outline a customized sort, known as Information
, which expects a
and b
to be strings.
perform sendData(a: quantity, b: quantity) {
return {
a: `${a}`,
b: `${b}`
}
}
sort Information = {
a: string,
b: string
}
perform consoleData(knowledge:Information) {
console.log(JSON.stringify(knowledge));
}
let stringifyNumbers = sendData(1, 2);
consoleData(stringifyNumbers);
Since consoleData
expects knowledge to be of format Information
, TypeScript throws an error if a
or b
are numbers. Our sendData
perform fixes that, by changing a
and b
to strings.
The difficulty with this setup is that if we added or modified sendData
, or our enter knowledge, then Information
would have to be up to date too. That is not an enormous deal, nevertheless it’s a simple supply of bugs. As such, we are able to as a substitute use ReturnType
to simplify our sort declaration. Our Information
sort could be written like so:
perform sendData(a: quantity, b: quantity) {
return {
a: `${a}`,
b: `${b}`
}
}
sort Information = ReturnType<typeof sendData>
// The identical as writing:
// sort Information = {
// a: string,
// b: string
// }
Since sendData
returns knowledge in sort { a: string, b: string }
, Information
turns into that sort. It means we do not have to keep up two copies of the output from sendData
– as a substitute we’ve got one, contained in the perform, and a sort that conforms to that, simplifying our code.