简体   繁体   中英

Calling nested overloaded function in Typescript

Given a nested overloaded function, such as innerOverloaded below, what is the best way to call it from a parent overloaded function that has similarly overloaded parameters as the inner one, as in the case with overloadedWithError ?

It seems that TypeScript can't figure out that the types are covariant (using the term somewhat loosely here).

function innerOverloaded(foo: true): false;
function innerOverloaded(foo: false): true;
function innerOverloaded(foo: boolean): boolean {
  return !foo;
}

function overloadedWithError(foo: boolean): boolean {
  return innerOverloaded(foo);
}

function overloadedButUgly(foo: boolean): boolean {
  return foo ? innerOverloaded(foo) : innerOverloaded(foo);
}

function overloadedButLessUgly(foo: boolean): boolean {
  return innerOverloaded(foo as true);
}

boolean is a union true | false true | false , as any union TS need something to narrow it down.

There is an open ticket about this: #14107 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM