[英]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.