Skip to content

Generic constraint extends is confusing #61694

@apetkov-so

Description

@apetkov-so

Acknowledgement

  • I acknowledge that issues using this template may be closed without further explanation at the maintainer's discretion.

Comment

Apologies if this has been asked before...

The extends generic constraint doesn't behave like its name suggests. E.g. <B extends A> does not mean "limit values to subclasses of A", but to just A. For example:

class Fruit {
    protected readonly name: string = ""
}

class Apple extends Fruit {
    name = "apple"
}

function eat<F extends Fruit>(f: F) {}

eat(new Apple()) // compiles, as expected - Apple does extend Fruit
eat(new Fruit()) // compiles, but it shouldn't - Fruit does not extend self

function eat2<F extends Fruit>(fruits: F[]) {
      for (const f of fruits) {
          // should compile but fails with "Property 'name' is protected...", as if `f` were just `Fruit`
          console.log(`eating ${f.name}...`)
    }
}

The extends constraint should actually limit values to subclasses.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions