如何创建一个类并在Typescript中动态添加字段?

时间:2019-12-19 11:52:40

标签: typescript nestjs

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

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

现在我的选项对象为

{
"firstName":"string
}

所以现在我想将此firstname属性添加到我的用户类中怎么做

2 个答案:

答案 0 :(得分:2)

这是答案,但不建议这样做。

由于向对象添加任意属性,使打字稿编译器无法为您检查潜在的错误。

class user {
    username: string = ""
    password: string = ""
}

let option = {
    "firstName": "string"
}

let myuser = new user()

for (let k of Object.keys(option)) {
    (myuser as any)[k] = (option as any)[k]
}

console.log(myuser)
// user {username: "", password: "", firstName: "string"}

答案 1 :(得分:1)

这是我的朋友。您只需要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}

But with nestjs! You should be able to do this anyway! Using metatypes :)

```typescript

@Controller()
export class TestController {
  @Post()
  test(
    @Body() test: TestClass,
 ): void {
   console.log(test); // should be instance of TestClass
 }
}

我可能是错的。您可能必须使用ValidationPipe或安装类转换器才能实现此目的,但始终对我有用,而且从未质疑过它!