question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Generic class validation

See original GitHub issue

Hello,

Is there any way to write validation on a generic class. Here an exemple of what I’d like to write :

export class ClassName<T> {
	@IsNotEmpty()
	@Expose()
	@IsArray()
	@ValidateNested({
		each: true,
	})
        @Type(() => T)
	public items: T[];
}

Do you have any idea ?

Thanks a lot for your answers 😃

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:14
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
MichalLytekcommented, Mar 3, 2020

Decorators are runtime artifact, hence why T doesn’t exist.

You should try create a class factory:

export function createMyClass<T>(Type: T) {
  class ClassName {
	@IsNotEmpty()
	@Expose()
	@IsArray()
	@ValidateNested({
      each: true,
	})
    @Type(() => Type)
	public items: T[];
  }
  return ClassName;
}

class Item {
  test: string;
}

const Test = createMyClass(Item);

It might not compile, it’s just an idea that works in TypeGraphQL 😄 https://19majkel94.github.io/type-graphql/docs/interfaces-and-inheritance.html#resolvers-inheritance

1reaction
janvennemanncommented, May 30, 2022

I ran into this as well today and was able to solve it using mixins. It works well for my use case, but you need to create intermediate types to map the singletons returned by the class expression pattern. So it’s not really viable when you have multiple properties that differ based on generics.

import 'reflect-metadata';
import { plainToClass, Type } from "class-transformer";
import { IsString, validate, ValidateNested } from "class-validator";

// We need to start out with a base class that we can extend
class BaseSearch {
  @IsString()
  searchId: string;
}

type Constructor<T = unknown> = new (...args: any[]) => T;

/**
 * Factory functions that returns a class expression which differs based on a generic
 */
function TypedSearch<
  TBase extends Constructor<BaseSearch>,
  TOptions
>(Base: TBase, OptionsClass: Constructor<TOptions>) {
  class TypedSearch extends Base {
    @ValidateNested()
    @Type(() => OptionsClass)
    options: TOptions;
  }
  return TypedSearch
}

class LocalizedSearchOptions {
   @IsString()
   currency: string;

   @IsString()
   locale: string;
}

class LocalizedSearch extends TypedSearch(BaseSearch, LocalizedSearchOptions) {}

async function main() {
  const instance = plainToClass(LocalizedSearch, {
    searchId: 'test',
    options: {
      currency: 'EUR',
    }
  })
  const errors = await validate(instance);
  console.log(errors);
}

main();
Read more comments on GitHub >

github_iconTop Results From Across the Web

TypeScript Generic with some validation | by Taufan - Medium
With generic, a single type can be reused with a variety of other types. Think of Promise , it can resolve to just...
Read more >
Java generic type validation - Stack Overflow
First we have the generic class that accepts any type as T with an abstract method that ... NotNull; import javax.validation.constraints.
Read more >
Generic data validation
Generic data can only be validated if it has a non-null DataType associated with it. When the DataType is null, the validation always...
Read more >
GenericValidator (Oracle Communications Billing Care Java ...
com.oracle.communications.brm.cc.validation.model.impl.GenericValidator<T> ... Generic Validator is the parent class for all Validator classes.
Read more >
Method Constraints with Bean Validation 2.0 - Baeldung
Cross-parameter constraints can be considered as the method validation equivalent to class-level constraints · Sometimes we'll need to validate ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found