简体   繁体   English

Typescript object 作为泛型键子集的键类型

[英]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?如何创建一个 object 并将键作为通用类型键的子集?

I need a type for the headers parameter that will be a subset of the keys of 'T' that maps to a string value.我需要 headers 参数的类型,它将是映射到字符串值的“T”键的子集。

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:您可以使用Record创建一个具有与T相同的键但属于string类型的类型,并使用Partial使键可选:

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 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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