Skip to content

⬅️ Back to Table of Contents

📄 getConstrainedTypeAtLocation

📊 Analysis Summary

Metric Count
🔧 Functions 1
📦 Imports 2

📚 Table of Contents

🛠️ File Location:

📂 packages/type-utils/src/getConstrainedTypeAtLocation.ts

📦 Imports

Name Source
ParserServicesWithTypeInformation @typescript-eslint/typescript-estree
TSESTree @typescript-eslint/typescript-estree

Functions

getConstrainedTypeAtLocation(services: ParserServicesWithTypeInformation, node: TSESTree.Node): ts.Type

Resolves the given node's type. Will return the type's generic constraint, if it has one.

Warning - if the type is generic and does not have a constraint, the type will be returned as-is, rather than returning an unknown type. This can be checked for by checking for the type flag ts.TypeFlags.TypeParameter.

See: https://github.com/typescript-eslint/typescript-eslint/issues/10438

Raw JSDoc
/**
 * Resolves the given node's type. Will return the type's generic constraint, if it has one.
 *
 * Warning - if the type is generic and does _not_ have a constraint, the type will be
 * returned as-is, rather than returning an `unknown` type. This can be checked
 * for by checking for the type flag ts.TypeFlags.TypeParameter.
 *
 * @see https://github.com/typescript-eslint/typescript-eslint/issues/10438
 */

Calls:

  • services.getTypeAtLocation
  • services.program .getTypeChecker() .getBaseConstraintOfType
Code
export function getConstrainedTypeAtLocation(
  services: ParserServicesWithTypeInformation,
  node: TSESTree.Node,
): ts.Type {
  const nodeType = services.getTypeAtLocation(node);
  const constrained = services.program
    .getTypeChecker()
    .getBaseConstraintOfType(nodeType);

  return constrained ?? nodeType;
}

Generated by Syntax Scribe