Skip to content

typeof something === 'function' No longer narrow certain generic typed variable to Function #54522

Closed
@thynson

Description

@thynson

Bug Report

typeof something === 'function' seems no longer narrow something to a Function in 5.1.3, when something has a generic type under certain circumstance.

🔎 Search Terms

typeof function

🕗 Version & Regression Information

The following code failed to compile on 5.1.3, while typescript prior to 5.0.4 works.
- This changed between versions 5.0.4 and 5.1.3

Updates:
The following code pass tsc before 4.7.4
fnLength1 is rejected by tsc since 4.8
methodFnLength is rejected by tsc since 5.1

⏯ Playground Link

Playground link

💻 Code

export function methodFnLength<T extends {}, K extends keyof T>(
  obj: T,
  methodKey: K,
): number {
  const fn = obj[methodKey];
  if (typeof fn !== 'function') {
    return 0;
  }
  return fn.length; // Since Typescript 5.1: fn has type T[K], instead of Function
}

export function fnLength1<T extends object>(
  fn: T
): number {
  if (typeof fn !== 'function') {
    return 0;
  }
  return fn.length; // Since Typescript 4.8: fn is narrowed to never
}

export function fnLength2<T>(
  fn: T
): number {
  if (typeof fn !== 'function') {
    return 0;
  }
  return fn.length; // okay
}

🙁 Actual behavior

It does not narrow fn to Function in all cases.

🙂 Expected behavior

It does narrow fn to Function in all cases as expected.

Metadata

Metadata

Assignees

Labels

Needs InvestigationThis issue needs a team member to investigate its status.

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions