typescript - 如何在打字稿中创建一个类并动态添加字段?
问题描述
我有一个类,我在其中获取选项作为参数,它是一个 JSON 对象,现在我想将此 JSON 对象的键作为属性添加到我现有的类中怎么做?例如我有一堂课
class user{
username: string,
password: string,
}
现在我的选项对象是
{
"firstName":"string
}
所以现在我想将这个名字属性添加到我的用户类中怎么做
解决方案
这个,我的朋友。你只需要https://github.com/typestack/class-transformer
类转换器可以将对象转换为具有给定原型和反向的类!使用 Expose 和 Exclude 装饰器:D
class TestClass {
@Exclude()
test: boolean = false;
@Expose()
showMe: boolean = true;
}
const data = {test: true, showMe: false};
console.log(data.constructor.prototype); // Object
const result = plainToClass(TestClass, data);
console.log(result.constructor.prototype); // TestClass
const response = classToPlain(result); // {showMe: false}
但是有了nestjs!无论如何,您应该能够做到这一点!使用元类型:)
@Controller()
export class TestController {
@Post()
test(
@Body() test: TestClass,
): void {
console.log(test); // should be instance of TestClass
}
}
我可能是错的。您可能必须使用 ValidationPipe 或安装类转换器来实现此目的,但始终为我工作并且从未质疑过!
推荐阅读
- javascript - 如何使用 jest 比较 excel 文件
- azure - 无法将 AAD 组添加到我的所有 DevOps 组织
- python - Tkinter 设置分离器的厚度
- sdk - LwIP DNS - 如何使用 DNS_LOOKUP_LOCAL_EXTERN?
- python - `import` 是否会在 Python 中产生运行时负担?
- json - VSCode 中出现“尾随逗号”错误
- deep-linking - Google Ads 应用互动广告系列不适用于 Firebase 动态链接
- dataframe - 加快将数据框转换为栅格的循环
- kubernetes - helm - 将 YAML 转换为 JSON 时出错:yaml:第 29 行:在此上下文中不允许映射值
- wso2carbon - WSO2 类调解器无法使用 wso2 集成工作室 8.0.0 添加 pom.xml