Skip to content

Add .isApplicableIndexType() to the TypeCheckerΒ #61886

Open
@mrazauskas

Description

@mrazauskas

πŸ” Search Terms

"isApplicableIndexType", "TypeChecker"

βœ… Viability Checklist

⭐ Suggestion

Please consider adding the .isApplicableIndexType() method to the TypeChecker.

πŸ“ƒ Motivating Example

Currently one can use .getStringIndexType() and .getNumberIndexType() available on the Type object. Those work fine, but do not include symbol and template string pattern index signatures that were introduced in TypeScript 4.4.

The change was made in #44512. The isApplicableIndexType() function was added in the PR, but it is not public. Here is how it looks:

function isApplicableIndexType(source: Type, target: Type): boolean {
    // A 'string' index signature applies to types assignable to 'string' or 'number', and a 'number' index
    // signature applies to types assignable to 'number', `${number}` and numeric string literal types.
    return isTypeAssignableTo(source, target) ||
        target === stringType && isTypeAssignableTo(source, numberType) ||
        target === numberType && (source === numericStringType || !!(source.flags & TypeFlags.StringLiteral) && isNumericLiteralName((source as StringLiteralType).value));
}

Simple enough, but not possible to reimplement, because of a tiny detail: numericStringType.

πŸ’» Use Cases

  1. What do you want to use this for?

I pass typeChecker.getIndexInfosOfType(sourceType) and want to check, if the targetType has an applicable index signature:

typeChecker
  .getIndexInfosOfType(sourceType)
  .some(({ keyType }) => typeChecker.isApplicableIndexType(targetType, keyType));
  1. What shortcomings exist with current approaches?

.getStringIndexType() and .getNumberIndexType() are available, but as mentioned above they do not cover all the cases. .isApplicableIndexType() could cover these, but it is not public.

  1. What workarounds are you using in the meantime?

Currently I am applying a patch that exposes .isApplicableIndexType(). That cannot work in long term unfortunately.

Also I have noticed that .getStringIndexType() and .getNumberIndexType() do not exist anymore in TypeScript 7. Might be worth to remove or at least to deprecate them in Strada as well. An alternative? Obviously: .typeChecker.isApplicableIndexType().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions