0

Consider the following interface:

interface User {
  id: number;
  name: string;
  email: string;
  address: {
    country: string;
    city: string;
    state: string;
    street: string;
  }
  active: boolean;
}

I need to create a generic PrimaryKey type, but it should correspond only to either string or number and omit any other type.

So in the case of PrimaryKey<User> only id, name, and email would be considered valid primary keys.

How do I achieve that?

Ruslan
  • 134
  • 1
  • 10
  • I recommend to read at following question: https://stackoverflow.com/questions/62158066/typescript-type-where-an-object-consists-of-exactly-a-single-property-of-a-set-o – MoxxiManagarm Jun 22 '22 at 16:13

1 Answers1

1

Maybe you can try this one:

interface User {
  id: number;
  name: string;
  email: string;
  address: {
    country: string;
    city: string;
    state: string;
    street: string;
  }
  active: boolean;
}

type ExtendedKeyOnly<T extends object, KeyType = string | number> = {
    [K in keyof T as T[K] extends KeyType ? K : never]: T[K];
};

type PrimaryKeyUser = ExtendedKeyOnly<User>;

type KeyOnlyPrimaryKeyUser = keyof PrimaryKeyUser;
Tiep Phan
  • 12,386
  • 3
  • 38
  • 41