首页 > 解决方案 > 如何在打字稿中创建一个类并动态添加字段?

问题描述

我有一个类,我在其中获取选项作为参数,它是一个 JSON 对象,现在我想将此 JSON 对象的键作为属性添加到我现有的类中怎么做?例如我有一堂课

class user{
username: string,
password: string,
}

现在我的选项对象是

{
"firstName":"string
}

所以现在我想将这个名字属性添加到我的用户类中怎么做

标签: typescriptnestjs

解决方案


这个,我的朋友。你只需要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 或安装类转换器来实现此目的,但始终为我工作并且从未质疑过!


推荐阅读