英文:
TS loop properties from Partial<Class> and set it to Class
问题
我有一个基本的JS类。一个非常简化的示例如下:
class Test {
a: number = 1;
b: string = 'foo';
populate(data){
for (let i in data) {
this[i] = data[i];
}
}
}
所以我基本上可以根据来自API的JSON数据填充实例。
const myClass = new Test();
myClass.populate({
a: 3,
b: 'hello world'
});
这一切都有效,并且已经在生产中使用了好几年(当然,包括hasOwnProperty
和typeof !== 'undefined'
检查等)。
我想在TypeScript中正确编写这个,但是我不知道如何做,因为一切都失败了。我尝试了很多次,但都没有成功,例如:
class Test {
a: number = 1;
b: string = 'B';
populate(data: Partial<Test>){
for(let i in data){
const v = data[i as keyof Partial<Test>];
if(v && Object.prototype.hasOwnProperty.call(this, i)){
this[i as keyof Test] = v; // error Type 'string' is not assignable to type 'never'.(2322)
}
}
}
}
const a = new Test();
a.populate({
a: 2,
b: 'bar'
});
除了使用//@ts-ignore
和[key: string]: any
之外(我希望避免使用any
),我能做些什么来使这个工作?
英文:
I have a basic JS class. A very heavily simplified example would be
class Test {
a: number = 1;
b: string = 'foo';
populate(data){
for (let i in data) {
this[i] = data[i];
}
}
}
So I can basically populate an instance based on JSON data from an API.
const myClass = new Test();
myClass.populate({
a: 3,
b: 'hello world'
});
This all works and is used in production for several years (of course with included hasOwProperty
and typeof !== 'undefined'
checks and so on).
I would like to properly code this in TypeScript, but I have no idea how, because everything fails. I had so many attempts with no avail, for example:
class Test {
a: number = 1;
b: string = 'B';
populate(data: Partial<Test>){
for(let i in data){
const v = data[i as keyof Partial<Test>];
if(v && Object.prototype.hasOwnProperty.call(this, i)){
this[i as keyof Test] = v; // error Type 'string' is not assignable to type 'never'.(2322)
}
}
}
}
const a = new Test();
a.populate({
a: 2,
b: 'bar'
});
What could I do except a //@ts-ignore
and [key: string]: any
(I would like to omit any
s) to make this working?
Here is my playground
答案1
得分: 2
class Test {
populate(data: Partial<Test>) {
Object.assign(this, data);
}
}
编辑:
在你描述的情况下,你可以尝试:
for (const [key, value] of Object.entries(data)) {
if(this.hasOwnProperty(key)) {
Object.assign(this, { [key]: value });
}
}
更好的解决方案可能是查看验证库,比如zod,这样你可以在代码中较早地捕获这种错误,而不是在达到populate
函数之前。
英文:
How about this
class Test {
populate(data: Partial<Test>) {
Object.assign(this, data);
}
}
EDIT:
In the case you described, you can try:
for (const [key, value] of Object.entries(data)) {
if(this.hasOwnProperty(key)) {
Object.assign(this, { [key]: value });
}
}
The better solution might be to look into validation libraries, such as zod, so that you can catch that sort of error earlier in your code, before it reaches the populate
function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论