Neok
Neok

Reputation: 770

Type of keys of a generic type with a given type

That's sound weird, so an exemple will defined the problem better:

Having a Model, I wan't the keys K where Model[K] is a given type GivenType (non generic).

So I guess a good start would be <Model, K extends keyof Model>, but this doesn't enforce Model[K] to be of type GivenType.

Upvotes: 0

Views: 42

Answers (1)

Neok
Neok

Reputation: 770

From documentation:

type NonFunctionPropertyNames<T> = {
  [K in keyof T]: T[K] extends Function ? never : K;
}[keyof T];

interface Part {
  id: number;
  name: string;
  subparts: Part[];
  updatePart(newName: string): void;
}

type T41 = NonFunctionPropertyNames<Part>; // "id" | "name" | "subparts"

So, in our case:

type ModelProperty<T> = {
  [K in keyof T]: T[K] extends Model ? K : never;
}[keyof T];

Upvotes: 1

Related Questions