microsoft / microsoft/TypeScript

Literal / Known keyof T (especially for mapped types)

Aperta
#40,600 4 commenti 2 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Suggestion
Lingua principale
Go
Stelle
111k
Fork
14.3k
Merge medio
2g 4h
PR unite (30g)
132

Descrizione

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.

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia con il Playground collegato e gli esempi di keyof/mapped-type per riprodurre il comportamento segnalato. Definisci la semantica proposta delle chiavi note per i casi generici e any, quindi determina le modifiche necessarie al compilatore TypeScript e la copertura necessaria affinché gli esempi si comportino come descritto.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
typescript
Ambito
compilers
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
28/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.