typescript - 使用打字稿类验证器进行(嵌套)索引签名
问题描述
我想验证(使用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 } }
. 但是让我们先从更简单的例子开始;-)
解决方案
由于装饰器不能附加到索引签名(在运行时不存在),您可以选择使用 Map来处理简单的情况。
class Example {
@IsInstance(Map)
@IsString({ each: true })
myProp: Map<string, string>;
}
推荐阅读
- android - 添加到应用程序中不存在请求的颤振引擎
- salesforce - 潜在客户分配规则
- angular - 具有布尔值/布尔值“平均值”的对象(更好的解释)
- html - materializecss 中的响应式图像问题
- javascript - 循环访问分析工具库中的特定 JS 代码
- tsql - 数值无法识别
- google-apps-script - 添加输入字段并连接到表格
- npm - 在“npm install”和“yarn install”上自动调用“node-gyp rebuild”
- python - 如何从 Python 中的 yml 文件中提取特定信息并在数据框中使用它?
- pytorch - 带有权重的pytorch conv2d