When working with TypeScript, it is important to remember that type guards must return a boolean value and nothing else. Any additional information must be handled separately.
Similarly, assertion functions face the same restriction - they can only throw errors or return void.
If you need to extract extra details beyond narrowing the type, you will have to handle it in a different part of your code, like so:
const result = checkType(value);
if (!result) {
const detail = getDetail(value);
// ...
}
While it is possible to assign outer scope variables to capture the desired information, such patterns are not considered functional and may pose challenges when ensuring TypeScript compatibility.
let detail: string;
function checkType(value: any): value is number {
if (typeof value === 'number') {
return true
} else {
reason = `Incorrect type: ${typeof value}`;
return false;
}
}