简体   繁体   中英

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?

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 .

I think you are looking for -

broken<Prefix>('Ms')

or

broken('Ms' as Prefix)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM