0

I have a method where the results type depends on the argument type. Using the ts type condition still results to some errors. what would be the correct code? and why is this wrong?

function foo<T>(v: T): T extends string ? number : boolean {
        if (typeof v === "string") return 12; // TS Error: Type '12' is not assignable to type 'T extends string ? number : boolean'.
        return true; // TS Error
    }   

const b = foo("bar"); // Ok

code in typescript playground

mbehzad
  • 3,758
  • 3
  • 22
  • 29
  • 4
    Does this answer your question? [TypeScript conditional return value type?](https://stackoverflow.com/questions/48808014/typescript-conditional-return-value-type) – jperl Feb 28 '21 at 22:28

1 Answers1

0
function foo(v: string): number;
function foo(v: any): boolean;
function foo(v: any): any {
    if (typeof v === "string") return 12;
    return true;
}
md2perpe
  • 3,372
  • 2
  • 18
  • 22