I know that in javascript I can copy the fields from an object to another object using Object.assign().
However, what I want to do is grab only the properties here in this interface:
export interface SizeOption {
width: number;
height: number;
unit: SizeUnit;
dpi?: number;
}
using assign doesn't help because I have getters and setters I need to grab not just the backing fields.
Object.create() grabs both fields and methods, but I would prefer to only grab stuff from the interface
Typescript interfaces only exist at compile time. You can't use them at runtime, you have to manually specify the properties to copy there:
function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {
const result = {};
for(const key of keys) result[key] = obj[key];
return result;
}
const result = pick(sizeOption, "weight", "height", "unit");
You can extract only the properties that you want from a more generic data object by using destructuring:
interface SizeOption {
width: number
height: number
dpi?: number
}
interface JSONData {
colors?:string
width:number
height:number
dpi?:number
title:string
source:string
}
// data from json has some unwanted properties
const data : JSONData = {
colors:"black",
height:300,
title:"help",
source:"img.jpg",
dpi:140,
width:400
}
// get only width height dpi from json
const {width, height, dpi} = data
// create sizeoption object
const size:SizeOption = {width, height, dpi}
console.log(size)
BTW your use case is not entirely clear. If you want a deep clone, why not use a class ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With