以下是一个通用的TypeScript函数示例,用于进行属性/字段映射:
function mapProperties(source: T, mapping: { [K in keyof U]: keyof T }): U {
const result = {} as U;
for (const key in mapping) {
const sourceKey = mapping[key];
result[key] = source[sourceKey];
}
return result;
}
这个函数接受两个参数:source
是源对象,mapping
是一个映射对象,用于指定源对象的属性与目标对象的属性之间的映射关系。
使用这个函数时,可以按照以下方式调用:
interface Source {
name: string;
age: number;
}
interface Target {
fullName: string;
yearsOld: number;
}
const source: Source = {
name: "Alice",
age: 30,
};
const mapping = {
fullName: "name",
yearsOld: "age",
};
const target: Target = mapProperties(source, mapping);
console.log(target); // { fullName: "Alice", yearsOld: 30 }
在这个例子中,我们定义了一个Source
接口和一个Target
接口,它们分别表示源对象和目标对象。然后,我们创建了一个source
对象,包含name
和age
属性。接下来,我们定义了一个mapping
对象,指定了源对象的name
属性应该映射到目标对象的fullName
属性,源对象的age
属性应该映射到目标对象的yearsOld
属性。
最后,我们调用mapProperties
函数,传入source
对象和mapping
对象,并将返回的结果赋值给target
对象。我们可以看到,target
对象的属性已经根据映射关系进行了赋值。
希望这个示例可以帮助你解决问题!