Home > Back-end >  Primary key type from typescript interface
Primary key type from typescript interface

Time:06-23

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?

CodePudding user response:

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;
  • Related