Skip to content

Narrowing of instanceof inconsistent with that oftypeof for Function types #37993

Closed
@jcao219

Description

@jcao219

https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#narrowing-functions-now-intersects--object-and-unconstrained-generic-type-parameters

TypeScript Version: 3.8.3

Search Terms:
narrowing instanceof
narrowing functions

Expected behavior:

instanceof should match typeof (intersect over unconstrained T)

Actual behavior:

divergence

Related Issues:

Code

function callOrNot1<T>(x: T | (() => T)): T {
  return typeof x === "function" ? /* correctly errors here */ x() : x;
}

function callOrNot2<T>(valOrFunc: T | (() => T)): T {
  return valOrFunc instanceof Function ? valOrFunc() : valOrFunc;
}

callOrNot2<() => string>(() => "")() // compiles, fails at runtime
Output
"use strict";
function callOrNot1(valOrFunc) {
    return typeof valOrFunc === "function" ? valOrFunc() : valOrFunc;
}
function callOrNot2(valOrFunc) {
    return valOrFunc instanceof Function ? valOrFunc() : valOrFunc;
}
callOrNot2(() => "")();
Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "declaration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": 2,
    "target": "ES2017",
    "jsx": "React",
    "module": "ESNext"
  }
}

Playground Link: Provided

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions