在TypeScrip中,我想创建一个泛型,我可以使用它将带有特定后缀的PropertyKeys添加到现有类型中.每个后缀也应该包含一个值的类型.以下代码说明了目标是什么:
// Example how to use
type OriginalType = {
name?: string;
age?: number;
// any other property
};
type ModifiedType = AddPostfixes<
OriginalType,
{ Postfix1: number; Postfix2: string; Postfix3: boolean } // here the Postfixes with their related type should be defined
>;
// current implementation
type AddPostfixes<T, Postfixes extends Record<string, any>> = {
[K in keyof T as `${K & string}${string &
keyof Postfixes}`]: K extends `${string & infer Prefix}${string &
keyof Postfixes}`
? Prefix extends keyof Postfixes
? Postfixes[keyof Postfixes]
: never
: K extends keyof T
? T[K]
: Postfixes[string & keyof Postfixes];
} & T;
// expected/prefered type for ModifiedType in this case
type ModifiedTypeExpected = {
namePostfix1?: number;
namePostfix2?: string;
namePostfix3?: boolean;
agePostfix1?: number;
agePostfix2?: string;
agePostfix3?: boolean;
} & OriginalType;
// actual type i have now for ModifiedType in this case
type ModifiedTypeActual = {
name?: string;
age?: number;
namePostfix1?: string;
namePostfix2?: string;
namePostfix3?: string;
agePostfix1?: number;
agePostfix2?: number;
agePostfix3?: number;
};
const m: ModifiedType = {};
export {};
附加注意:当基键中的前缀为可选时,添加的前缀必须是可选的. 因此,即
type MyOriginalType = {
name: string;
age?: age;
}
// agePostfix1, agePostfix2, agePostfix3 has to be optional too
type PostfixedType = AddPostfixes<MyOriginalType>;
生成的后缀键也应该是可选的.
感谢您对修复泛型类型AddPostfixes
的任何帮助.