Tane Piper
Tane Piper

Reputation: 1151

Returning a typed let value from Typescript async await method?

I have the following code inside my main file for a command line app:

const init = async (): Promise<types.IContextObject> => {
  let context: types.IContextObject;
  try {
      context = await createContext(dataObj);
  } catch (e) {
      dataObj.errors.insert({ message: e.message });
      process.exit(1);
  }

  context.info.insert({
    message: `Using Rules: `.bold + `${Object.keys(context.rules).join(', ')}`
  });
  return context;

};

In this I get the following compiler error:

Variable 'context' is used before being assigned.
let context: types.IContextObject

If I move the last two lines inside the try block I get:

Function lacks ending return statement and return type does not include 'undefined'.

Upvotes: 1

Views: 737

Answers (2)

user8086575
user8086575

Reputation:

Your variable context is undefined outside of the try block. Either move your insert and return inside of the try block and return null in your catch, or set context to null when you declare it; however, if you do the latter without proper null checks after your catch statement, it could throw an error when attempting to access info.

Upvotes: 1

Simon Meskens
Simon Meskens

Reputation: 968

If you put it outside the try, there's no guarantee that value exists. If you put it in the try, you have to provide a second return method, so that it returns something when the try fails.

So either you provide a default value for context or you provide a default return statement at the bottom. Either of these works fine.

Upvotes: 3

Related Questions