TypeScript: Inconsistent TS2345 error when using function generics

Bug Report

πŸ”Ž Search Terms

  • Inconsistent 2345
  • function generics
  • extends 2345
  • generics 2345

πŸ•— Version & Regression Information

  • This changed from version 4.7.4+ and above

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

function func<T extends { foo: 1 }>(arg: T): void {}

func({ foo: 1, bar: 1 });

πŸ™ Actual behavior

bar property sometimes displayed as valid and sometimes produce an error:

Argument of type '{ foo: 1; bar: number; }' is not assignable to parameter of type '{ foo: 1; }'.
  Object literal may only specify known properties, and 'bar' does not exist in type '{ foo: 1; }'.(2345)

When playing with the code live and change bar to bar222 or ba sometimes the error shown and sometimes not. Refreshing the playground link with the changes always remove the error.

https://user-images.githubusercontent.com/534911/190869020-376ff387-56ff-48b3-83e4-43261b2b4d78.mov

πŸ™‚ Expected behavior

Always display as valid without any error.

{ foo: 1, bar: 1 } is a valid subtype of { foo: 1 } and so can legally be used to instantiate T.


Maybe related to https://github.com/microsoft/TypeScript/issues/49490

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 18 (10 by maintainers)

Most upvoted comments

I was using the editor with TS built from different commits. I was doing that within the TS repo itself so I could pretty easily jump between commits/builds

@OxleyS unfortunately, this looks like a different problem, especially given the call stack shared here

Expected behavior: Always display an error for unknown properties.

The correct behavior is for there to be no error here: excess property checks aren’t intended to apply to generic constraints. { foo: 1, bar: 1 } is a valid subtype of { foo: 1 } and so can legally be used to instantiate T.