Skip to content

Type 'a'|'b' is assignable to 'a' in overwriting method signature of subclass #15391

Closed
@janv

Description

@janv

TypeScript Version: 2.2.2

Code

// Working Example
function Baz(x: 'a' | 'b') {
    var y:'a' = x
}
// This correctly errors:
// Type '"a" | "b"' is not assignable to type '"a"'.
//  Type '"b"' is not assignable to type '"a"'.

// Failing Example
class Foo {
  x(x:'a'|'b'):void {}
}

class Bar extends Foo {
  x(x:'a'):void {}
}

var foo:Foo = new Foo()
var bar:Foo = new Bar()

foo.x('b')
bar.x('b') // Whoa there!

Playground link

Expected behavior:
The extension of class Foo by Bar should fail because the signatures of the x method implementations are incompatible as illustrated in the last 4 lines.

  • Calling Foo.x with 'b' is allowed.
  • We should be able to transparently substitute instances of Foo with instances of Bar since Bar is a subclass of Foo
  • But Bar.x does not accept 'b' as an argument

Actual behavior:

Typescript doesn't complain and let's me extend Foo with Bar.

As seen in the Baz function, checking assignability of Unions seems to work in other cases but apparently not in the case of method overwriting by a subclass.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions