I would like to validate (using class-validator) a class having an index signature:
class Example {
myProp: { [foo: string]: string }
}
I would like to make sure the myProp.something and myProp.somethingElse are actually strings, not number, objects, arrays, ...
Any idea how to do this?
One approach was to use a separate class an IsString() like this:
class MyProp {
@IsString()
[foo: string]: string
}
class Example {
@IsDefined()
@ValidateNested()
myProp: MyProp
}
However, typescript won't compile: Decorators are not valid here.
Actually I would also like to validate types like { [foo: string]: { [bar: string]: string } }. But let's start with the easier example first ;-)
Since decorators cannot be attached to index signatures (which do not exist at runtime), you can alternatively use a Map for the simple case.
class Example {
@IsInstance(Map)
@IsString({ each: true })
myProp: Map<string, string>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With