首页 > 其他分享 >[Typescript] Function Overloads vs. Union Types

[Typescript] Function Overloads vs. Union Types

时间:2023-01-31 19:44:35浏览次数:47  
标签:Function function Typescript return string generator Overloads runGenerator run

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

相关文章