代码中的函数TestFunc 应该在任何情况下都返回string。我认为这是一种错字。让我们修复它并继续。
后来我想出了一个更安全的解决方案(我将旧答案留在了底部)。最好使用重载。在重载中描述条件逻辑,在函数中使用联合类型。
interface MyType {
name: string;
}
function testFunc<T extends MyType | string>(
what: T
): T extends MyType ? string : MyType;
function testFunc(what: MyType | string): MyType | string {
if (typeof what === 'object') {
return what.name;
}
return { name: what };
}
旧答案:
interface MyType {
name: string;
}
type TestFunc = <T extends MyType | string>(what: T) => T extends MyType ? string : MyType;
const testFunc: TestFunc = (what: any) => {
if (typeof what === 'object') {
return what.name;
}
return { name: what };
};
或者如果你更喜欢定义内联类型:
interface MyType {
name: string;
}
const testFunc: <T extends MyType | string>(what: T) =>
T extends MyType ? string : MyType =
(what: any) => {
if (typeof what === 'object') {
return what.name;
}
return { name: what };
};
Typescript 编译器会这样处理它:
const a1: MyType = testFunc({ name: 'foo' }); // Type 'string' is not assignable to type 'MyType'.
const a2: MyType = testFunc({ name: 1 }); // Error: Argument of type '{ name: number; }'
// is not assignable to parameter of type 'string | MyType'
const a3: string = testFunc({ name: 'foo' }); // Ok
const a4: string = testFunc('foo'); // Error: Type 'MyType' is not assignable to type 'string'.
const a5: MyType = testFunc('foo'); // Ok