简体   繁体   中英

In typescript, How to use a generic to constraint and describe return value type of function?

Look the code,I think tom is type of BB extends AA, So it should be work

Code Error: TS2322: Type 'BB' is not assignable to type 'T'

interface AA {
    name: string
}
interface BB extends AA{
    age: number
}
const tom: BB = {
    name: 'tom',
    age: 20
}
function something<T extends AA>(): T {
    return tom
}

How can I use like

something<BB>() 

to get a value which extends AA; Or

something<CC>() 

which CC extends AA

Your identify function should look like this:

interface AA {
    name: string
}
interface BB extends AA{
    age: number
}
const tom: BB = {
    name: 'tom',
    age: 20
}
function identity<T extends AA>(arg: T) {
    return arg
}

identity(tom)

The problem with you current implementation is that you are using a specific kind of type T .

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