microsoft / microsoft/TypeScript

Literal / Known keyof T (especially for mapped types)

Abierto
#40,600 4 comentarios 2 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.4k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

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.

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con el Playground enlazado y los ejemplos de keyof/mapped-type para reproducir el comportamiento reportado. Define la semántica propuesta de claves conocidas para los casos genéricos y any, y determina después los cambios necesarios en el compilador de TypeScript y la cobertura necesarios para que los ejemplos se comporten como se describe.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
typescript
Área
compilers
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
28/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.