TypeScript: How to write a function with conditional return type

前端 未结 3 540
既然无缘
既然无缘 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 17:49

    The problem is inside the function T is not known, so you can't really assign a value to Value<T>. One option would be to use a type assertion. A more type safe option would be to use a separate implementation signature, that would be more relaxed about the input and output type:

    export function create<T extends string | number>(value: T): Value<T> // public signature
    export function create(value: string | number): Name | Id { // more relaxed private implementation signature 
        if (typeof value === "string") return { name: value }
    
        return { id: value }
    }
    
    0 讨论(0)
  • 2021-01-01 17:55

    I'm not sure I understand your example fully, but I think this is what you want?

    type Name = { name: string }
    type Id = { id: number }
    type Value = Name | Id
    
    export function create(value: string | number): Value {
      if (typeof value === "string") return { name: value }
      return { id: value }
    }
    

    See, that I've removed any generics from your example, since I don't see the need for them in this case

    0 讨论(0)
  • 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 | number> = T extends string ? Name : Id
    
    export function create<T extends string | number>(value: T): Value<T> {
        if (typeof value === 'string') return { name: value } as unknown as Value<T>
    
        return { id: value } as unknown as Value<T>
    }
    
    0 讨论(0)
提交回复
热议问题