Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using typescript class-validator for (nested) index signature

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 ;-)

like image 901
some-user Avatar asked Mar 20 '26 10:03

some-user


1 Answers

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>;
}
like image 178
Trevor Kropp Avatar answered Mar 22 '26 08:03

Trevor Kropp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!