Skip to content Skip to sidebar Skip to footer

Typescript How To Copy Only Properties And Methods From Interface To A New Object?

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 interfac

Solution 1:

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");

Solution 2:

You can extract only the properties that you want from a more generic data object by using destructuring:

interfaceSizeOption {
    width: numberheight: number
    dpi?: number
}

interfaceJSONData {
    colors?:stringwidth:numberheight:number
    dpi?:numbertitle:stringsource:string
}

// data from json has some unwanted propertiesconst data : JSONData = {
    colors:"black",
    height:300,
    title:"help",
    source:"img.jpg",
    dpi:140,
    width:400
}

// get only width height dpi from jsonconst {width, height, dpi} = data

// create sizeoption objectconstsize: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 ?

Post a Comment for "Typescript How To Copy Only Properties And Methods From Interface To A New Object?"