Skip to content

Unsafe declaration of resolve function in Promise constructor #22040

Closed
@ikokostya

Description

@ikokostya

TypeScript Version: [email protected]

Search Terms:

Promise, resolve

Code

function f(): Promise<number> {
    return new Promise((resolve) => {
        resolve();
    });
}

tsconfig.json:

{
    "compilerOptions": {
        "module": "commonjs",
        "moduleResolution": "node",
        "target": "es2017",
        "lib": ["es2017"],
        "alwaysStrict": true,
        "noEmitOnError": true,
        "pretty": true,
        "strict": true
    }
}

Expected behavior:

Compile error: undefined is not assignable to number.

Actual behavior:

No errors.

Playground Link: http://www.typescriptlang.org/play/index.html#src=function%20f()%3A%20Promise%3Cnumber%3E%20%7B%0A%20%20%20%20return%20new%20Promise((resolve)%20%3D%3E%20%7B%0A%20%20%20%20%20%20%20%20resolve()%3B%0A%20%20%20%20%7D)%3B%0A%7D

Looks like this happens, because resolve() function in Promise executor takes optional argument https://github.com/Microsoft/TypeScript/blob/b3edc8f9f4d9cf4203c4c4493e4f0f3dc96c845d/lib/lib.es2015.promise.d.ts#L33

The provided example is correctly checked by Flow: https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVUCuA7AxgFwEs5swoAKASgC4wAFAJzgFtCBnAUwB5tNmAjDgwB8YAN6owUsAw75MDUtg5JGLdh3LlZbODABuHSmAC8oidMsyOug5soBuSdIC+j1C9RA


I trying to change declaration (i.e. make value parameter of resolve function is required) and the following code stop working:

function bar(): Promise<void> {
    return new Promise((resolve) => {
        resolve(); // Expected 1 arguments, but got 0.
    });
}

In Flow this code also works without error https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVUCuA7AxgFwEs5swAjAQwCcAKASgC4wAFKuAW0IGcBTAHgBucQgBMAfGADeqMLLBUe+TFVLYeSVh248aNBVzgwBPOmAC8E6XOvyeBozroBuGXIC+z1G6A

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions