Open
Description
Suggestion
π Search Terms
- keyof
- keyofStringsOnly
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript codeThis wouldn't change the runtime behavior of existing JavaScript codeThis could be implemented without emitting different JS based on the types of the expressionsThis isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
Since pattern literal types like `${number}`
are valid as of #40598, I feel like there should be an option to make:
type ArrayLikeKeys = keyof ArrayLike<any>;
result in:
type ArrayLikeKeys = "length" | `${number}`;
The same should happen for any numeric property key:
interface Foo {
1: "a";
2: "b";
3: "c";
}
// Currently is: : 1 | 2 | 3
// Should be: "1" | "2" | "3"
type KeyOfFoo = keyof Foo;
// Currently is: never
type StrictKeyOfFoo = (keyof Foo) & (string | symbol);
like with:
interface Foo {
"1": "a";
"2": "b";
"3": "c";
}
// Is: "1" | "2" | "3"
type KeyOfFoo = keyof Foo;
π Motivating Example
This makes keyof
and numeric index signatures match runtime behaviour.
π» Use Cases
Currently, itβs necessary to use the strictKeyof
and StrictPropertyKey
helpers:
type strictKeyof<T> = keyof T extends infer K
? (K extends number ? `${K}` : K)
: never;
type StrictPropertyKey = string | symbol;
Relevant issues:
- Mapped tuples types iterates over all properties #27995
- fix(lib/es2015): Fix definition of
ProxyHandler
#35594 (comment), fix(lib/es2015): Fix definition ofProxyHandler
#35594 (comment), fix(lib/es2015): Fix definition ofProxyHandler
#35594 (comment) - keyof object is number instead of string #41669
- fix(lib/es2015): Fix types of
Reflect
methods #41987 - Improve support for numeric string types #48837
- Design Meeting Notes, 4/27/2022 #48957
This will most likely depend on #26797, so that treating numeric index signatures as numeric pattern literal index signatures is valid:
interface ArrayLike<T> {
readonly [index: `${number}`]: T;
readonly length: number;
}
Metadata
Metadata
Assignees
Labels
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity