Microsoft/TypeScript

Surprising `Not all code paths return a value`

Open

#18.319 aperta il 7 set 2017

Vedi su GitHub
 (8 commenti) (13 reazioni) (0 assegnatari)TypeScript (6726 fork)batch import
Help WantedSuggestion

Metriche repository

Star
 (48.455 star)
Metriche merge PR
 (Merge medio 6g 17h) (9 PR mergiate in 30 g)

Descrizione

TypeScript Version: 2.5.2

Code

type AsyncFunction<T> = () => Promise<T>;

const f: AsyncFunction<number | void> = async () => {
  if (Math.random()) {
    return 1;
  }
};

Expected behavior:

No tsc errors.

Actual behavior:

const f: AsyncFunction<number | void> = async () => {
//                                      ~~~~~~~~~~~~~ [ts] Not all code paths return a value.

  if (Math.random()) {
    return 1;
  }
};

Notably, when using return-type annotation, this error does not occur:

async function a(): Promise<number | void> {
  if (Math.random()) {
    return 1;
  }
}

const b = async (): Promise<number | void> => {
  if (Math.random()) {
    return 1;
  }
};

In our real-world scenario, it would not be sufficient to look for this syntactic pattern. Rather, the fact that the async function is assigned to a union containing void should be the trigger that silences this error.

Guida contributor