Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

An alternative option to keyofStringsOnly that stringifies numeric properties and index signatures #43041

Open
5 tasks done
ExE-Boss opened this issue Mar 2, 2021 · 0 comments
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript

Comments

@ExE-Boss
Copy link
Contributor

ExE-Boss commented Mar 2, 2021

Suggestion

🔍 Search Terms

  • keyof
  • keyofStringsOnly

✅ Viability Checklist

My suggestion meets these guidelines:

  • 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 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:


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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

2 participants