考虑以下接口:
interface User {
id: number;
name: string;
email: string;
address: {
country: string;
city: string;
state: string;
street: string;
}
active: boolean;
}
我需要创建一个泛型PrimaryKey类型,但它应该只对应于字符串或数字,而省略任何其他类型。
因此在PrimaryKey<User>
的情况下,只有id、name和email被认为是有效的主键。
我如何做到这一点?
也许你可以试试这个:
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;