Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS1055 when using async/await using a type alias

Tags:

typescript

I have declared a type alias:

export type ActivationPromise = Promise<void>;

I have written the following functions:

async function derp(): ActivationPromise {
    await test();
}

function test() : ActivationPromise {
    return Promise.resolve();
}

My tsconfig.json:

{
    "compilerOptions": {
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "module": "commonjs",
        "target": "es5",
        "allowJs": true,
        "alwaysStrict": true,
        "importHelpers": true,
        "lib": [ "dom", "es5", "es2015.promise", "es2015.iterable", "scripthost"]
    },
    "compileOnSave": false
}

When I compile, I get:

error TS1055: Type 'ActivationPromise' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor

If I change the return type to simply Promise<void>, the code compiles fine. Only when using the type alias, the issue happens. Since the type alias should just function as a typedef, why does this happen?

like image 942
Sebazzz Avatar asked Aug 27 '17 08:08

Sebazzz


People also ask

Is not a valid async function return type in ES5 ES3 because?

ts(28,23): error TS1055: Type 'boolean' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.

Is await should always be used with async?

Note: The await keyword is only valid inside async functions within regular JavaScript code. If you use it outside of an async function's body, you will get a SyntaxError .

Can we use await only with promises?

You can only usefully await a promise. map will return an array, so you can't usefully await it. If someFunction returns a promise, then the map will return an array of promises, which you could wrap with Promise.

Does async await stop execution?

await is usually used to unwrap promises by passing a Promise as the expression . Using await pauses the execution of its surrounding async function until the promise is settled (that is, fulfilled or rejected). When execution resumes, the value of the await expression becomes that of the fulfilled promise.


1 Answers

error TS1055: Type 'ActivationPromise' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor

Suggestion

Refrain from type aliasing promises 🌹

Fix

If you alias, make sure you have a value backing it as well which will be the mentioned Promise-compatible constructor instance:

export type ActivationPromise = Promise<void>;
export const ActivationPromise = Promise<void>;
like image 119
basarat Avatar answered Oct 08 '22 20:10

basarat