typescript - 如何复制对象

标签 typescript

我正在用 typescript 编写一个应用程序,并且我正在尝试强类型 Object.assign 调用,如下所示:

let obj = new Author();
let x = Object.assign({}, obj);

我希望变量x 的类型为Author。不幸的是它是Object类型。

如果我这样做,我会得到一个正确的类型:

Object.assign<Author, Author>(new Author(), obj);

我什至可以简化第一个类型参数:

Object.assign<{}, Author>(new Author(), obj);

但是,这非常冗长(我需要手动指定类型),并迫使我在分配之前创建一个 Author 对象。还有其他方法可以实现这一目标吗?或者是否有其他方法可以在保留其原型(prototype)的同时复制 typescript 中的对象?

最佳答案

你的意思是这样的吗?也许我误解了你的问题,但是像这样,你可以很好地组合类型/值退出

let test = {name: "value"};
let item = {hallo: "hallo", ...test};

类似的东西也正在工作

// could be also defined as class
type Author = {name: string, value: string}

let authorValue = {value: "value"}
let authorName = {name: "name"}

let author: Author = {...authorName, ...authorValue};

当然,instanceof 不会工作,因为这些类型不会被转译。

这里还有一些测试

class Author {
    constructor(public name, public value) {}
}
let authorName = {name: "name"}
let author = new Author("Franz", "Value");
let combined: Author = { ...author, ...authorName }
// false
console.log(combined instanceof Author);
Object.assign(author, authorName);
// true
console.log(author instanceof Author);

关于typescript - 如何复制对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44088168/

相关文章:

html - 如果我单击 Angular 中的类,则隐藏 div

typescript - 如何正确定义嵌套对象的泛型类型

Angular 双向绑定(bind)以从输入字段获取总计

angular - RxJs6:OperatorFunction 与 MonoTypeOperatorFunction

node.js - TsLint 提示调用顶级异步方法

typescript - 确保 TypeScript 联合在整个代码中保持狭窄

typescript - 在 TypeScript 中使用引号和不使用引号声明模块有什么区别?

node.js - 使用字符串键和函数值定义对象的类型

javascript - 两个日期之间的独特 1 步差

javascript - Angular/Typescript 无法设置未定义的属性 'data'