gpt4 book ai didi

javascript - Typescript 对象的构造函数中 Object.assign() 的目的是什么?

转载 作者:搜寻专家 更新时间:2023-10-30 21:33:34 24 4
gpt4 key购买 nike

在此过程中,我向我的 Todo 类添加了一个构造函数:

export class Todo {
id: number;
title: string;
complete: boolean = false;
editMode: boolean = false;

constructor(values: Object = {}) {
Object.assign(this, values);
}
}

我不明白构造函数中代码的用途。

我的应用程序似乎在有和没有它的情况下都能正常工作,但我对删除代码犹豫不决

这个构造函数中 Object.assign(...) 的目的是什么?

最佳答案

这是一种方法,可以轻松地将类的参数值添加到类实现该接口(interface)或至少部分植入该接口(interface)的类字段中。

interface IPerson {
firtName: string;
lastName: string;
}

class Person implements IPerson {
public firtName!: string;
public lastName!: string;

constructor(params: IPerson) {
Object.assign(this, params);
}
}

您的应用程序可以运行,因为您似乎已经以 values 的回调值也足够的方式实现了这一点。

这个 Hack 的主要问题是 Object.assign is not type safe .所以以这种方式使用它在某种程度上违背了 TypeScript 的观点。

如果您想以类型安全的方式执行此操作,最好使用正确检查类型的自定义实现。像这样:

type PDM = PropertyDescriptorMap;

export class ClassSAssign<T> {
constructor(private objectToSpread: T, private klass: T) {}

private propertyDescriptorOptions = {
enumerable: true,
writable: true
};

public apply(): void {
const map = this.getPropertiesDescriptorMap();
Object.defineProperties(this.klass, map);
}

private getPropertiesDescriptorMap(): PDM {
return Object.entries(this.objectToSpread).reduce(
(obj: PDM, entry) => this.getPropertyDescriptorMap(obj, entry),
{}
);
}

private getPropertyDescriptorMap(obj: PDM, [key, value]: [string, any]): PDM {
return {
...obj,
[key]: {
value,
...this.propertyDescriptorOptions
}
};
}
}

您可以像这样使用此实用程序:

class Person implements IPerson {
public firtName!: string;
public lastName!: string;

constructor(params: IPerson) {
new ClassSAssign(params, this).apply();
}
}

如果你不想/不能使用上面的内容,我建议你至少添加一些类型严格性来保护你的类免受可以传递给它的值的影响

interface IToDo {
id?: number;
title?: string;
}

export class Todo implements IToDo {
public id?: number;
public title?: string;
public complete: boolean = false;
public editMode: boolean = false;

constructor(values?: IToDo) {
Object.assign(this, values);
}
}

关于javascript - Typescript 对象的构造函数中 Object.assign() 的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55583732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com