Typescript type guard that returns additional data
Asked Answered
B

1

6

is it possible for a type guard function to return other data?

For example something like this:

function isNumber(value: any): [value is number, reason: string] {
    if (typeof value === 'number') {
        return [true, ""]
    } else {
        return [false, `Wrong typeof ${typeof value}`]
    }
}
Bechtold answered 26/2, 2022 at 17:9 Comment(1)
No, you can't do this, see github.com/microsoft/TypeScript/issues/46650 for a relevant feature request. There are refactorings that give you similar behavior, but I don't know if you care about them.Furuncle
L
5

TypeScript requires that the return value of a type guard be a boolean, and nothing else. There's no room for any other information.

An assertion function has the same sort of problem - it must either throw or return void, nothing else.

If you want to extract any information other than the type narrowing you want, you'll have to do it elsewhere - such as

const result = isNumber(value);
if (!result) {
  const reason = getReason(value);
  // ...
}

I suppose you could assign to an outer scope variable to get what you want, but such constructions aren't functional and are often more difficult to get TypeScript to play well with.

let reason: string;
function isNumber(value: any): value is number {
    if (typeof value === 'number') {
        return true
    } else {
        reason = `Wrong typeof ${typeof value}`;
        return false;
    }
}
Livvyy answered 26/2, 2022 at 17:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.