sirisian / ecmascript-types

ECMAScript Optional Static Typing Proposal http://sirisian.github.io/ecmascript-types/
453 stars 4 forks source link

Typed promises. #57

Closed sirisian closed 2 years ago

sirisian commented 3 years ago

WIP issue as I've been meaning to include a section about this, but I haven't gotten around to thinking about it.

A typed Promise in generic syntax looks like:

Promise<R:any, E:any>

There's a resolve type and an reject (exception) type that defaults to any.

const a = new Promise<uint8, Error>((resolve, reject) => {
  return 0; // or throw new Error();
});

In async function syntax:

async function F():uint8 {
  return 0;
}

This intuitively creates a return type of Promise<uint8, any>.

Questions raised about this would be is this the correct syntax and thinking? The thrown exception will basically always be any unless the programmer explicitly knows that all used function calls will return a specific exception type.

There's no syntax right now in the async function for defining the reject type. Not sure what syntax would be ideal.

An example of another language that has such syntax though is Java with its throws keyword. Using such syntax here we'd have:

async function F():uint8 throws Error {
  return 0;
}

Now the return is Promise<uint8, Error>.

sirisian commented 2 years ago

This is now in the https://github.com/sirisian/ecmascript-types/blob/master/README.md#typed-promises along with further details.