microsoft / microsoft/TypeScript

Literal / Known keyof T (especially for mapped types)

Open
#40,600 4 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

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

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked Playground and the keyof/mapped-type examples to reproduce the reported behavior. Define the proposed known-key semantics for generic and any cases, then determine the TypeScript compiler changes and coverage needed for the examples to behave as described.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
28/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.