admin管理员组

文章数量:1401384

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

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

Share Improve this question asked Jul 8, 2019 at 9:39 James Joshua StreetJames Joshua Street 3,41911 gold badges50 silver badges87 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

Typescript interfaces only exist at pile 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 ?

本文标签: javascripttypescript how to copy only properties and methods from interface to a new objectStack Overflow