Skip to content

Unable to narrow Promise return types #43378

Closed
@andparsons

Description

@andparsons

Bug Report

I am expecting to get a compiler error when the return type of a promise does not match exactly.

Currently the wrapping of a type in a Promise changes the behaviour of the type narrowing, instead allowing for additional properties to be declared outside the defined type.

🔎 Search Terms

promise, return-type, type-narrowing

🕗 Version & Regression Information

4.2.3

⏯ Playground Link

Playground link with relevant code

💻 Code

For a normal object, I can get the compiler error as expected with the following:

interface SingleProperty {
  aSingleProperty: string
}
const willErrorAsExpected: SingleProperty = {
  aSingleProperty: "aString",
  anAdditionalPropertyThatShouldCauseAnError: "aString",
}

When working with a Promise, it seems that additional properties on the type are allowed, even though the compiler will error as expected if the return does NOT include all required properties in the type.

interface SingleProperty {
  aSingleProperty: string
}
const willNotErrorAsExpected: Promise<SingleProperty> = new Promise<void>((resolve) => {
  setTimeout(() => {
    resolve()
  }, 1)
}).then(() => {
  return {
    aSingleProperty: "aString",
    anAdditionalPropertyThatShouldCauseAnError: "aString",
  }
})

const willErrorAsExpected: Promise<SingleProperty> = new Promise<void>((resolve) => {
  setTimeout(() => {
    resolve()
  }, 1)
}).then(() => {
  return {
    theWrongProperty: "aString",
  }
})

🙁 Actual behavior

The willNotErrorAsExpected const should trigger a compiler error when a property that is additional to it's promised return type, but does not

🙂 Expected behavior

When explicitly specifying the promise return type, the behaviour should match that of a non-promise in the way the type narrows what is allowed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions