Skip to content

Generic bounds not enforced on generic argument #32330

Closed
@evmar

Description

@evmar

TypeScript Version: typescript@3.6.0-dev.20190710, 3.5.1

Search Terms: generic bounds toString

Code

function f1<T>(o: T) {
  o.toString(); // error
  // This is expected, because T might be undefined or null
}

function f2<T extends {}>(o: T) {
  o.toString(); // no error
  // This is expected, this is the correct way to fix the above function.
}

function user<T>(t: T) {
  f1(t);  // Allowed, but irrelevant because f1() is invalid
  f2(t);  // Allowed?  <- this is the bug
  t.toString();  // Error, expected for the same reason as f1()
}

Expected behavior:
You should not be able to pass an arbitrary T into a function that demands T extends {}.

Actual behavior:
Despite .toString() being disallowed both in user() and in f1(), you can just pass it to f2() and still call toString on the same value.

Playground Link:
http://www.typescriptlang.org/play/#code/GYVwdgxgLglg9mABMAjAHgCoD4AUcBciGAlIgN4BQiicAdFHAMpQBOMYA5jsQNwUC+FCqEiwEyAEyZEAUwAeUGWAAmAZ3L9cBIqUrU6DZm07c+g4eGjwkIVTJaZcUQiXJVkKHFF7vgErz7UUPRMrOxcPuZAA

Related Issues:

Metadata

Metadata

Assignees

Labels

Breaking ChangeWould introduce errors in existing codeBugA bug in TypeScriptFix AvailableA PR has been opened for this issueRescheduledThis issue was previously scheduled to an earlier milestone

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions