打字稿 - 按值进行自定义类型分配
在我的一个过程中,我需要定期重置自定义类型,但我注意到Typescript(也许也可以在JavaScript中),当我将自定义类型的变量分配给同一类型的另一个变量时,分配是通过参考而不是通过价值制作。
例如,此代码:
type testing = {
a: string;
b: number;
};
let v1: testing = { a: "one", b: 1 };
let v2: testing = { a: "two", b: 2 };
console.log(v1);
console.log(v2);
v1 = v2;
v1.a = "Edited";
console.log(v1);
console.log(v2);
生成此输出
{ a: 'one', b: 1 }
{ a: 'two', b: 2 }
{ a: 'Edited', b: 2 }
{ a: 'Edited', b: 2 }
可以通过值分配它而不分配类型的每个属性?
(在我的示例中,我需要我的V2变量保持等于{a:“两个”,b:2})
In one of my procedures I need to periodically reset a custom type, but I noticed that in TypeScript (and I think in JavaScript too maybe), when I assign a variable of a custom type to another variable of the same type, the assignment is made by reference and not by value.
For example this code:
type testing = {
a: string;
b: number;
};
let v1: testing = { a: "one", b: 1 };
let v2: testing = { a: "two", b: 2 };
console.log(v1);
console.log(v2);
v1 = v2;
v1.a = "Edited";
console.log(v1);
console.log(v2);
generates this output
{ a: 'one', b: 1 }
{ a: 'two', b: 2 }
{ a: 'Edited', b: 2 }
{ a: 'Edited', b: 2 }
Is there a way to assign it by value without assigning every property of the type?
(in my example I need my v2 variable to remain equals to { a: "two", b: 2 })
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于这样的简单案例,您可以使用传播操作员创建对象的浅副本。
请注意这里有一些警告。如Tobias的评论中的链接所示,这只会进行浅副本。如果您有更复杂的对象,这将引起问题。
For simple cases like this, you can make use of the spread operator to create a shallow copy of an object.
Note there are some caveats here. As indicated by the link in Tobias S' comment, this will only do a shallow copy. If you have more complex objects, this will cause issues.