首页 > 解决方案 > 使用打字稿类验证器进行(嵌套)索引签名

问题描述

我想验证(使用class-validator)具有索引签名的类:

class Example {
  myProp: { [foo: string]: string }
}

我想确保 myProp.something 和 myProp.somethingElse 实际上是字符串,而不是数字、对象、数组......

知道怎么做吗?

一种方法是使用一个单独的类,IsString()如下所示:

class MyProp {
  @IsString()
  [foo: string]: string
}

class Example {
  @IsDefined()
  @ValidateNested()
  myProp: MyProp
}

但是,打字稿不会编译:Decorators are not valid here.

其实我也想验证像{ [foo: string]: { [bar: string]: string } }. 但是让我们先从更简单的例子开始;-)

标签: typescriptclass-validator

解决方案


由于装饰器不能附加到索引签名(在运行时不存在),您可以选择使用 Map来处理简单的情况。

class Example {
    @IsInstance(Map)
    @IsString({ each: true })
    myProp: Map<string, string>;
}

推荐阅读