簡體   English   中英

Typescript object 作為泛型鍵子集的鍵類型

[英]Typescript object key type as a subset of the keys of a generic type

如何創建一個 object 並將鍵作為通用類型鍵的子集?

我需要 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',
    });
  }
}

您可以使用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',
    });
  }
}

游樂場鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM