TypeScript: How to write a function with conditional return type

前端 未结 3 543
既然无缘
既然无缘 2021-01-01 17:37
export type Name = { name: string }
export type Id = { id: number }
export type Value = T extends string ? Name : Id

export function create

        
3条回答
  •  無奈伤痛
    2021-01-01 18:07

    Here is another solution which works great as well.

    I like this solution better than the accepted answer because you will get correct type deduction when coding:

    You can see when hovering, it correctly deduced the type.

    Here is the code from the screenshot:

    export type Name = { name: string }
    export type Id = { id: number }
    export type Value = T extends string ? Name : Id
    
    export function create(value: T): Value {
        if (typeof value === 'string') return { name: value } as unknown as Value
    
        return { id: value } as unknown as Value
    }
    

提交回复
热议问题