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 badges2 Answers
Reset to default 3Typescript 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
?
版权声明:本文标题:javascript - typescript how to copy only properties and methods from interface to a new object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744282692a2598730.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论