我正在用 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/