Typescript generics constraint is not working

Viewed 47
type PossibleValues = 'a' | 'b';
type Convert<T extends PossibleValues> = T extends 'a' ? string : number;

function myFunc<T extends PossibleValues>(param1: T): Convert<T> {
    if (param1 === 'a') {
        return 'someString'; // why can't I return a string?
    } else {
        return 0; // why can't I return a number?
    }
}

const testString = myFunc('a'); // type is string
const testNumber = myFunc('b'); // type is number

Typescript generic is not working in the above case. I'm trying to return string or number based on certain conditions, but ts throws error when returning.

What is strange is that variable such as testString and testNumber gets the correct type definition. Any help is appreciated

TS Playground link

0 Answers
Related