镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Union type method parameters in base class accepts incompatible types in subclass overrides #19832

Description

Using union types in base class method declarations allows override functions that only declare one of the union member types. This produces code that crashes at runtime, even with --strict.

TypeScript Version: 2.7.0-dev.20171108

Code

abstract class Base {
    abstract foo(arg: string | number): boolean
}

class C extends Base {
    foo(arg: string): boolean {
        return arg.startsWith("a")
    };
}

const a: Base = new C()
a.foo(1)

Expected behavior:

Should not compile.

Actual behavior:

Compiles and crashes at runtime.

Activity

  1. ahejlsberg commented on Nov 8, 2017

    @ahejlsberg
    Member
  2. asmundg commented on Nov 8, 2017

    @asmundg
    MemberAuthor

    Aha, I had missed the part where --strictFunctionTypes does not apply to methods. I take it I should stay away from inheritance if I want contravariant parameter checking then.

  3. locked and limited conversation to collaborators on Jun 14, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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