Created
March 17, 2024 11:24
-
-
Save isocroft/3db59a2b48e6376088bcf0ea256f685f to your computer and use it in GitHub Desktop.
Using assertion signatures to validate data from external sources using the Yup validation/schema library
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
import Yup from "yup"; | |
import type { InferType } from "yup"; | |
const UserSchema = Yup.object({ | |
name: Yup.string().required(), | |
email: Yup.string().email().required(), | |
fullname: Yup.string().required(), | |
title: Yup.string().required(), | |
gender: Yup.string().required().default("male"), | |
rating: Yup.number().min(1).max(10).required(), | |
birthdate: Yup.date().required(), | |
is_active: Yup.boolean().default(false), | |
}) | |
/* @HINT: extract typecript type from Yup Schema */ | |
type User = InferType<typeof UserSchema> | |
/* @NOTE: assertion signature function */ | |
function isUser (user: unknown): user is User { | |
return UserSchema.isType(user) | |
} | |
const getAgeBandFor = (user: unknown) => { | |
/* @HINT: assertion of `user` object passed in as argument */ | |
if (isUser(user)) { | |
const today = new Date(); | |
const age = user.birthdate.getFullYear() - today.getFullYear() | |
switch(true) { | |
case age >= 30 && age <= 39: | |
return "millennial"; | |
case age >= 60 && age <= 89: | |
return "boomer"; | |
case age >= 20 && age <= 29: | |
return "gen-z"; | |
default: | |
return "unknown" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment