Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to make a TypeScript function return never (or throw) if a generic type extends a subtype without casting?

(There is no genuine use-case here, so this is my code)

I’m trying to make a function that throws an error if the string is "fish". I was successfully able to do this by using as, however,
is there any way to avoid using as for this scenario?

function throwIfFish<S extends string>(string: S): S extends "fish" ? never : S {
    if (string === "fish") {
        throw new Error("fish");
    }
    return string as S extends "fish" ? never : S;
    //            ^ is this unavoidable?
}

Typescript Playground

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The conditional type in question is simple enough, and the result type is "good enough" so that index signature type can work here:


type NeverFish<S extends string> = {
    fish: never;
    [n: string]: S;
}

function throwIfFish<S extends string>(str: S): NeverFish<S>[S] {
    if (str === "fish") {
        throw new Error("fish");
    } else { 
        return str; 
    }
}


let r1 = throwIfFish("f");    // "f"
let r2 = throwIfFish("fish"); // never


Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading