Skip to content

instanceof type guard fails with a static toString method #27276

Closed
@chharvey

Description

@chharvey

TypeScript Version: 3.0.3
Options: --strict --noImplicitAny --noImplicitThis --noImplicitReturns --target="ES2017" --module="CommonJS"

Search Terms: instanceof type guard class "toString"

Code:

declare class Thing { static toString(thing: any): string; } // <!-- here’s the problem
declare class Person extends Thing { name: string; }
declare class Robot extends Thing { serial: number; }

function test(smart_thing: Person|Robot): number {
	if (smart_thing instanceof Robot) {
		return smart_thing.serial // typeof `smart_thing` is Person|Robot,
		                          // and getting `.serial` fails
	} else return 0
}

Expected behavior:

The type of smart_thing should be narrowed to Robot.

Actual behavior:

The type of smart_thing has not been narrowed from Person | Robot.

When the static method Thing.toString is renamed or removed, or its parameter is deleted, the problem goes away.

Playground Link:

TypeScript Playground

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions