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:

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 ?


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