错误是
Type '(str: string, convert?: unknown) => { result: number; } | { result: string; }' is not assignable to type 'X'.
Type '{ result: number; } | { result: string; }' is not assignable to type '{ result: string; }'.
Type '{ result: number; }' is not assignable to type '{ result: string; }'.
Types of property 'result' are incompatible.
Type 'number' is not assignable to type 'string'.
interface X {
(str: string): {
result: string
}
(str: string, convert: true): {
result: number
}
}
const func: X = (str, convert = false) => {
if (convert) return {
result: parseInt(str, 10)
}
return {
result: str
}
}
请查看函数重载的文档。
function x(str: string): string;
function x(str: string, convert=true): number;
function x(str: string, convert?: boolean) {
if (convert) {
return parseInt(str, 10);
}
return str;
}