microsoft / microsoft/TypeScript

Literal / Known keyof T (especially for mapped types)

Offen
#40,600 4 Kommentare 2 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Suggestion
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.3k
Ø Merge
2 T. 4 Std.
Gemergte PRs (30 T.)
132

Beschreibung

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");
*/

Playground

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.

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit dem verknüpften Playground und den keyof/mapped-type-Beispielen, um das gemeldete Verhalten zu reproduzieren. Definiere die vorgeschlagene Semantik für bekannte Schlüssel in generischen und any-Fällen und ermittle anschließend die erforderlichen Änderungen am TypeScript-Compiler und an der Testabdeckung, damit sich die Beispiele wie beschrieben verhalten.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
typescript
Bereich
compilers
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
28/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.