Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object returned from a function can have keys not present in its return type #50064

Closed
Dwlad90 opened this issue Jul 27, 2022 · 3 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@Dwlad90
Copy link

Dwlad90 commented Jul 27, 2022

Bug Report

When a function is typed to return an object of a certain type, the properties of the object can be expanded, meaning extra properties can be added to the ones described in the type or interface.

🔎 Search Terms

function return object type

🕗 Version & Regression Information

This is observable on the playground in all available versions.

Couldn't find anything I understood to be relevant in https://github.com/Microsoft/TypeScript/wiki/FAQ#common-bugs-that-arent-bugs

  • This is a crash: No
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about interfaces and types of function return values

⏯ Playground Link

Buggy example on @next

💻 Code

interface Result {
    foo: string;
}

type Func = () => Result

const noError:Func = () => ({
  foo: 'string1',
  // @ts-expect-error
  bar: 2,
});

const error:Func = (): Result => ({
  foo: 'string1',
  // @ts-expect-error
  bar: 2,
});

const error2:Func = (): ReturnType<Func> => ({
  foo: 'string1',
  // @ts-expect-error
  bar: 2,
});

🙁 Actual behavior

Extra properties in the returned object, which aren't defined in the interface or type, do not raise an error.

🙂 Expected behavior

Extra properties in the returned object, which aren't defined in the interface or type, should raise an error.

@MartinJohns
Copy link
Contributor

MartinJohns commented Jul 27, 2022

This is not a bug. The return type is not specified, so it's inferred. The inferred return type is then checked for compatibility, and it's compatible. This comes up pretty often, e.g. #41850.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jul 27, 2022
@RyanCavanaugh
Copy link
Member

See also #241

@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants