如题,希望类型转换后的对象能只有自己本身的属性,不保留多余属性如
// 转换的类
class A {
text:string
id:number
}
class ADTO {
text:string
other:string
}
let aDTO = new ADTO()
aDTO.text = 'text'
aDTO.other = "other"
// 希望有个transfrom插件
// 让a是A类型的,内容是 {text:'text'},得到从aDto相同的属性,不保留不同的属性
const a = transform(A, new ADTO())
###
可以定义一个接口来负责传输目标类,另外有点麻烦的地方在于因为要引用Object.keys(),得给目标类的各个属性加上一个默认值:
interface TransformInterface {
}
class A {
text:string = null
id:number = null
}
class B {
other:string = null
id:number = null
}
class ADTO {
text:string
other:string
}
let aDTO = new ADTO()
aDTO.text = 'text1'
aDTO.other = "other1"
function transform(param: ADTO, tmp: TransformInterface): any {
Object.keys(tmp).forEach(key=>tmp[key]=param[key]);
return tmp
}
let objA = transform(aDTO, new A())
let objB = transform(aDTO, new B())
console.log(objA)
console.log(objB)
希望能帮助到你。