Sometimes, we want to set the return type for the array map method callback in TypeScript.
In this article, we’ll look at how to set the return type for the array map method callback in TypeScript.
How to set the return type for the array map method callback in TypeScript?
To set the return type for the array map method callback in TypeScript, we can set the return type of the callback with type assertion.
For instance, we write
interface IKeys {
key1: string;
key2: string;
}
array.map(
(val) =>
<IKeys>{
key1: val.key1,
key2: val.key2,
}
);
to create the IKeys
interface.
Then we call array.map
with a callback that returns an IKeys
object.
We set the return type of the callback with <IKeys>
in front of the callback.
Conclusion
To set the return type for the array map method callback in TypeScript, we can set the return type of the callback with type assertion.