Typescript 深度克隆只读实例
假设我们有一个类,它的属性引用了另一个类。我希望能够深度克隆它的“不可变”(或Typescript 深度克隆只读实例,typescript,immutability,deep-copy,Typescript,Immutability,Deep Copy,假设我们有一个类,它的属性引用了另一个类。我希望能够深度克隆它的“不可变”(或只读)实例: import * as _ from 'lodash'; interface IParent{ name: string; } interface IChild{ name: string; parent: IParent; } public class Child implements IChild{ public name: string; public pare
只读
)实例:
import * as _ from 'lodash';
interface IParent{
name: string;
}
interface IChild{
name: string;
parent: IParent;
}
public class Child implements IChild{
public name: string;
public parent: string;
constructor(props: IChild){
Object.assign(this, props);
}
toImmutable(): Readonly<IChild> {
return _.cloneDeep(this); //lodash deep clone
}
}
有没有一个优雅的解决方案可以让我将克隆对象上的所有内容都设置为只读
注:
看起来
lodash
有一个名为cloneDeepWith
的方法,它接受一个“customizer”。。。想知道这是否是正确的方向 关键是创建一个自定义类型DeepReadonly
,您可以使用它来代替Readonly
:
类型DeepReadonly={
只读[K in keyof T]:DeepReadonly;
}
此类型将递归地将readonly属性应用于所有嵌套对象
类型DeepReadonly={
只读[K in keyof T]:DeepReadonly;
}
从“lodash”导入*as uuu;
接口iPart{
名称:字符串;
}
接口IChild{
名称:字符串;
父母:IParent;
}
类子类实现了IChild{
公共名称:字符串;
公共家长:IParent;
建造师(道具:IChild){
分配(这个,道具);
}
toImmutable():DeepReadonly{
return u.cloneDeep(this);//lodash deep clone
}
}
let child=新的子对象({
姓名:“abc”,
父项:{name:“123”}
});
设immutable=child.toImmutable();
immutable.name='abc'//不准
immutable.parent.name='abc'//不准
您应该考虑通过使用<代码> Read Ong/Cux>属性来执行不可变性。这让你的生活变得更加轻松,因为它允许你在不改变原始对象的情况下执行浅拷贝。+很好的副作用:浅拷贝速度更快,节省成本memory@ideaboxerohhh如此深的克隆变得不必要了,因为如果引用的对象是不可变的,它就不需要被克隆?是的,明白了。顺便说一句,这是默认的工作方式:默认情况下,所有属性和本地“变量”(常量)都是只读的,但它仍然是一种成熟的编程语言。epic!仅供参考,您发布的游乐场链接将我带到.net文档页面仅供参考,此解决方案存在一些大问题。。。在此详细讨论:
let child = new Child({
name: 'abc',
parent: { name: 123 }
});
let immutable = child.toImmutable();
immutable.name = 'abc'; //not allowed
immutable.parent.name = 'abc'; //this is allowed!!!
type DeepReadonly<T> = {
readonly [K in keyof T]: DeepReadonly<T[K]>;
}
type DeepReadonly<T> = {
readonly [K in keyof T]: DeepReadonly<T[K]>;
}
import * as _ from 'lodash';
interface IParent{
name: string;
}
interface IChild{
name: string;
parent: IParent;
}
class Child implements IChild{
public name: string;
public parent: IParent;
constructor(props: IChild){
Object.assign(this, props);
}
toImmutable(): DeepReadonly<IChild> {
return _.cloneDeep(this); //lodash deep clone
}
}
let child = new Child({
name: 'abc',
parent: { name: "123" }
});
let immutable = child.toImmutable();
immutable.name = 'abc'; //not allowed
immutable.parent.name = 'abc'; //not allowed