microsoft / microsoft/TypeScript
Literal / Known keyof T (especially for mapped types)
Personne n'a encore pris cette issue.
- Langage dominant
- Go
- Étoiles
- 111k
- Forks
- 14.4k
- Merge moyen
- 1 j 19 h
- PR mergées (30 j)
- 117
Description
Search Terms
literal known keyof union primitive subtract subtraction generic mapped exact
Suggestion
keyof T has issues with mapped types when T is generic but still has known keys.
The resulting mapped type has indeterminate keys despite having some of the keys known.
It would be helpful to be able to map the known keys only in order to have a determinate result type.
Propose adding something like a known keyof operator that would resolve to only the known/literal keys of an object.
Use Cases
Would like to use this to validate property / object compatibility, especially with the upcoming recursive conditional types.
A major use case is supporting property path tuples (or dotted paths, as shown in the example in https://github.com/microsoft/TypeScript/pull/40336)
Having known keyof would allow validation of a path tuple parameter recursively without having to generate all the possible valid values for a type (quickly running into the union cap).
type _DottedPath<T, K extends string & keyof T = string & keyof T> = K extends any ? K | `${K}.${_DottedPath<NonNullable<T>[K]>}` : never;
type DottedPath<T> = _DottedPath<T>;
//This one is unworkable
type PathGetterExpensive<T> = <TPath extends DottedPath<T>>(obj: T, path: TPath) => PropType<T, TPath>;
//This should work
type PathGetter<T> = <TPath extends string>(obj: T, path: OnlyIfPathCompatible<T, TPath>) => PropType<T, TPath>;
//Playground link below has an example of this using `keyof` instead of `known keyof`, and the issue it causes
type OnlyIfPathCompatible<T, TPath extends string, TOut = TPath> =
TPath extends known keyof T ? TOut :
TPath extends `${infer K}.${infer R}` ? (K extends known keyof T ? OnlyIfPathCompatible<T[K], R, TOut> : never) :
never;
Another use case is catching issues where a type T has been inferred to any unexpectedly and I would prefer a parameter of type keyof T to be never rather than keyof any.
Examples
type Obj = { a: number; b: number; c: string; };
type KeysByType<O, T> = { [k in keyof O]-?: O[k] extends T ? k : never; }[keyof O];
type KeyofExtends<T extends Obj> = keyof T; //indeterminate - which can be a problem.
type NumericProps<T extends Obj> = KeysByType<T, number>; //indeterminate - which can be a problem.
function contrivedIssue<T extends Obj>(obj: T) {
const k: keyof T = "a";
const numericK: KeysByType<T, number> = "a"; //Error, though it shouldn't be.
const va: number = obj.a; //Because TS already knows that T has property `a` of type `number`.
return [numericK, va];
}
/*
// Proposed: `known keyof`
type KnownKeyofExtends<T extends Obj> = known keyof T; // "a" | "b" | "c";
type KnownKeyofAny = known keyof any; // never;
type KnownKeysByType<O, T> = { [k in known keyof O]-?: O[k] extends T ? k : never; }[known keyof O];
type KnownNumericProps<T extends Obj> = KnownKeysByType<T, number>; // "a" | "b";
*/
//Another real world use case is catching when inferred to any.
function multiplyPropsG<T>(obj: T, propA: KeysByType<T, number>, propB: KeysByType<T, number>) {
//@ts-expect-error
return obj[propA] * obj[propB];
}
//Good
const axb = multiplyPropsG({ a: 1, b: 2 } as const, "a", "b");
//@ts-expect-error - Good
const axbInvalid = multiplyPropsG({ c: 1, d: 2 } as const, "a", "b");
//@ts-expect-error - Preferably
const axbAny = multiplyPropsG({ c: 1, d: 2 } as any, "a", "b");
/*
function multiplyKnownPropsG<T>(obj: T, propA: KnownKeysByType<T, number>, propB: KnownKeysByType<T, number>) {
return obj[propA] * obj[propB];
}
//This would be an error
const axbKnownAny = multiplyKnownPropsG({ c: 1, d: 2 } as any, "a", "b");
*/
Checklist
My suggestion meets these guidelines:
- [X ] This wouldn't be a breaking change in existing TypeScript/JavaScript code
- [X ] This wouldn't change the runtime behavior of existing JavaScript code
- [X ] This could be implemented without emitting different JS based on the types of the expressions
- [X ] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- [X ] This feature would agree with the rest of TypeScript's Design Goals.
Guide de contribution
Ouvrir le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Piste de recherche
Commencez par le Playground associé et les exemples de keyof/mapped-type afin de reproduire le comportement signalé. Définissez la sémantique proposée des clés connues pour les cas génériques et any, puis déterminez les modifications du compilateur TypeScript et la couverture nécessaires pour que les exemples se comportent comme décrit.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- typescript
- Domaine
- compilers
- Type d'issue
- Fonctionnalité
- Difficulté
- 5/5
- Temps estimé
- Plus d'une semaine
- Activité
- À l'abandon
- Clarté
- Plutôt claire
- Accessibilité débutants
- 28/100