typescript类型条件导致不可分配错误



我有一个方法,其中结果类型取决于参数类型。使用ts类型条件仍然会导致一些错误。正确的代码是什么?为什么这是错的?

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

playground

function foo(v: string): number;
function foo(v: any): boolean;
function foo(v: any): any {
if (typeof v === "string") return 12;
return true;
}

最新更新