简体   繁体   中英

Typescript object key type as a subset of the keys of a generic type

How do I create an object with keys as a subset of the keys of a generic type?

I need a type for the headers parameter that will be a subset of the keys of 'T' that maps to a string value.

export abstract class Table<T> {
  constructor(
    protected data: T[],
    //this requires the headers object to contain all the keys in T
    protected headers: { [key in keyof T]: string },

    //but I need something like this
    protected headers: { [keyof T]: string }
  ) {}
  //...abstract methods
}

//example
interface User {
  username: string;
  password: string;
  age: number;
}

class UserTable extends Table<User> {
  constructor(data: User[]) {

    //this does not compile since it does not contain all the keys from User
    super(data, {
      username: 'User',
      age: 'Age',
    });
  }
}

You can use Record to create a type with the same keys as T but of string type and Partial to make the keys optional:

export abstract class Table<T> {
  constructor(
    protected data: T[],
    //this requires the headers object to contain all the keys in T
    protected headers: Partial<Record<keyof T, string>>,
  ) {}
  //...abstract methods
}

//example
interface User {
  username: string;
  password: string;
  age: number;
}

class UserTable extends Table<User> {
  constructor(data: User[]) {

    //this does not compile since it does not contain all the keys from User
    super(data, {
      username: 'User',
      age: 'Age',
    });
  }
}

Playground Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM