Get the return type of a function in TypeScript
Sometimes you only want to rely on the return type of a function instead of defining a new type for it.
To do that in TypeScript use ReturnType
and typeof
:
function extractStatusData(buffer: Buffer) {
return {
active: buffer[0] !== 1,
totalErrors: buffer[1]
}
}
function onStatusChange(callback: (data: ReturnType<typeof extractStatusData>) => void) {
listenToSomeBinaryStuff(buffer => {
const statusData = extractStatusData(buffer)
callback(statusData)
});
}
onStatusChange(({active, totalErrors}) => {
if (active) {
console.log(`Task is still running`)
} else {
console.log(`Task is completed with ${totalErrors} errors`)
}
})
Tweet