gpt4 book ai didi

typescript - 如何在 typescript 中创建对象时通过传递JSON来初始化构造函数参数

转载 作者:搜寻专家 更新时间:2023-10-30 22:03:28 25 4
gpt4 key购买 nike

假设我有一个类

export class PersonName {
constructor(
public firstName: string = "",
public lastName: string = "",
public middleName: string = "",
) { }
}

我想通过在创建对象时传递 json 对象来初始化在构造函数中声明的这些变量。

例如:

var person = new Person({
"firstName" : "abc",
"lastName" : "xyz",
"middleName" : ""
});

最佳答案

一种方法是为构造函数提供重载,然后测试第一个参数是字符串还是包含字段的对象:

export class Person {
public firstName;
constructor(
firstName: string,
lastName: string,
middleName: string,
);
constructor(
person: { firstName: string, lastName: string, middleName: string }
);
constructor(
arg1: string | { firstName: string, lastName: string, middleName: string } = "",
public lastName: string = "",
public middleName: string = "",
) {
if (typeof arg1 === "string") {
this.firstName = arg1;
} else {
this.firstName = arg1.firstName;
this.lastName = arg1.lastName;
this.middleName = arg1.middleName;
}
}
}

const person = new Person({
"firstName": "",
"lastName": "",
"middleName": "",
});
const person2 = new Person("foo", "bar", "baz");

关于typescript - 如何在 typescript 中创建对象时通过传递JSON来初始化构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44697202/

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