Description
π Search Terms
"isApplicableIndexType", "TypeChecker"
β Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β 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
- 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));
- 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.
- 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()
.