简体   繁体   English

typescript如何仅将属性和方法从接口复制到新对象?

[英]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(). 我知道在javascript中,我可以使用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. 使用assign无济于事,因为我有getter和setter方法,我不仅需要抓住支持领域。

Object.create() grabs both fields and methods, but I would prefer to only grab stuff from the interface Object.create()可以同时获取字段和方法,但是我更喜欢仅从接口中获取内容

Typescript interfaces only exist at compile time. Typescript接口仅在编译时存在。 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 ? 如果要deep clone ,为什么不使用class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM