Union type:
function runGenerator(generator: { run: () => string } | (() => string)) {
if (typeof generator === 'function') {
return generator();
}
return generator.run();
}
vs
function overload:
function runGenerator(generator: { run: () => string }): string;
function runGenerator(generator: () => string): string;
function runGenerator(generator: { run: () => string } | (() => string)) {
if (typeof generator === 'function') {
return generator();
}
return generator.run();
}
When the function return type is the same, we should condier to use Union type.
But when the function return type is different based on input arguement, then we should condier to use function overload:
function runGenerator(generator: { run: () => string }): { result: string };
function runGenerator(generator: () => string): string;
function runGenerator(
generator: { run: () => string } | (() => string)
): string | { result: string } {
if (typeof generator === 'function') {
return { result: generator() };
}
return generator.run();
}
标签:Function,function,Typescript,return,string,generator,Overloads,runGenerator,run From: https://www.cnblogs.com/Answer1215/p/17080295.html