Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stricter return type for makeValidator #114

Merged
merged 1 commit into from
Dec 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
coverage
npm-debug.log
yarn-error.log
2 changes: 1 addition & 1 deletion src/envalid.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export function cleanEnv<T>(
* Create your own validator functions.
*/
export function makeValidator<T>(
parser: (input: string) => any,
parser: (input: string) => T,
type?: string
): (spec?: Spec<T>) => ValidatorSpec<T>

Expand Down
21 changes: 19 additions & 2 deletions tests/envalid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,25 @@ const inferredEmail: string = strictEnv.email
// const invalidField: string = strictEnv.nonsense

// Custom validator
const validator = makeValidator<Number>((input: string) => 3.33, 'CUSTOM_TYPE')
validator({
const validator = makeValidator<number>((input: string) => 3.33, 'CUSTOM_TYPE')
const validatorSpec = validator({
default: 3.33,
desc: 'Test Validator'
})
const shouldBeNum: number = validatorSpec._parse('3')
// const shouldNotBeString: string = validatorSpec._parse('56')

function isArrayOfStrings(arr: any[]): arr is string[] {
return arr.every(s => typeof s === 'string')
}

const validatorThatThrows = makeValidator<string[]>((input: string) => {
const arrStr = JSON.parse(input)
if (!Array.isArray(arrStr)) throw new Error('Should be an array!')
if (!isArrayOfStrings(arrStr)) {
throw new Error('Should be strings!')
}
return arrStr
}, 'CUSTOM_TYPE')

// const badValidator = makeValidator<number>((input: string) => '3.33', 'CUSTOM_TYPE')