Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support non-bool assertions #57941

Closed
6 tasks done
kkmuffme opened this issue Mar 25, 2024 · 1 comment
Closed
6 tasks done

Support non-bool assertions #57941

kkmuffme opened this issue Mar 25, 2024 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@kkmuffme
Copy link

πŸ” Search Terms

assertion is typeguard

βœ… Viability Checklist

⭐ Suggestion

Currently only the is syntax with a bool return is supported.

Asserting on non-bool return should be possible to return the type one expects to avoid having to write separate assertion functions.

πŸ“ƒ Motivating Example

function getString<const T>(arg: T): T extends string ? T : false {
    if ( typeof arg === 'string' ) {
        return arg;
    }

    return false;
}

function isString(val: any): val is string {
  return typeof val === "string";
}

function t1(arg: string|number): string {
    if ( getString(arg) === false ) {
        const y = arg; // should be number
        return '';
    }

    const z = arg; // should be string
    return '';
}

function t2(arg: string|number): string {
    const u = getString(arg);
    if ( u === false ) {
        const y = u;
        return '';
    }

    const z = u;
    return '';
}

function t3(arg: string|number): string {
    if ( isString(arg) === false ) {
        const y = arg;
        return '';
    }

    const z = arg;
    return '';
}

πŸ’» Use Cases

We already have a getString function in the codebase, which technically does assert something but typescript is unaware of it.
Now instead we have to write a separate is assert function which does the same thing, bloating the codebase unnecessary and increasing the maintenance burden.
You could argue that we should is functions only in the first place - however this would create lots of redundant code - where we could do just return getString(arg); we have to do return isString(arg) ? arg : false; which is the reason why there is "get" function in the first place.

@jcalz
Copy link
Contributor

jcalz commented Mar 25, 2024

Assertion functions and user-defined type guard functions are different, but you seem to be using the former term to refer to the latter.

Duplicate of #46650, found via repo:microsoft/TypeScript boolean guard in:title

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Mar 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants