Skip to content

Instantly share code, notes, and snippets.

@vitkon
Created October 6, 2017 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitkon/e3d4558867144f5e09a31f0c08608bb2 to your computer and use it in GitHub Desktop.
Save vitkon/e3d4558867144f5e09a31f0c08608bb2 to your computer and use it in GitHub Desktop.
Validation with TS Generics
function isRequired<T extends string> (prop: T, message: string = `${prop} is a required field`) {
return [
(model: { [name in T]: any }) => !!model[prop],
{ [prop as string]: message }
];
}
interface Foo {
price: 123;
desc: 'foo';
}
export type FooKeys = keyof Foo;
const a = isRequired<FooKeys>('price');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment