Skip to content
Advertisement

Why can’t I return a string literal type in TS

I don’t understand the following error:

type Prefix = 'Ms' | 'Mrs' | 'Mr'

const broken = <T extends Prefix>(prefix: T): T => {
    // do something
    return 'Ms';  
 
    // If I do `return 'Ms' as 'Ms'` then it works

}

const works = <T extends Prefix>(prefix: T): T => {
    // do something
    return p;
}

const alsoWorks = (): Prefix => {
    // do something
    return 'Ms';
}

The method broken is giving me

Type ‘”Ms”‘ is not assignable to type ‘T’. ‘”Ms”‘ is assignable to the constraint of type ‘T’, but ‘T’ could be instantiated with a different subtype of constraint ‘Prefix’.

Not sure why this method doesn’t work, but the other two do?

Advertisement

Answer

TypeScript is complaining that the following call will not work:

const res: 'Mr' = broken<'Mr'>('Mr');

If T is instantiated to something else than Ms, your return 'Ms' is violating the the return type T.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement