Created
October 6, 2017 22:00
-
-
Save vitkon/e3d4558867144f5e09a31f0c08608bb2 to your computer and use it in GitHub Desktop.
Validation with TS Generics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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