Created
September 8, 2023 04:11
-
-
Save justsml/8d2e80c974abe3ee244e8dd54638cab4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
export type User = ReturnType<typeof verifyUser>; | |
// ^ Type defined for 'free' | |
// + Pro: Less wasted effort aligning types AND validation. | |
// + Pro: More 'honest', not obscured by layers, `any` or `as` | |
// - Con: Easy to accidentally change a public interface. | |
// (Prefer explicit definitions at your library/module boundaries.) | |
export function verifyUser(data: { [key: string]: unknown; }) { | |
if (!data || typeof data !== 'object') | |
throw new Error(`User must be a valid object.`); | |
return { | |
id: Number(expected(data, 'id')), | |
name: String(get(data, 'name')), | |
email: formatEmail(get(data, 'email')), | |
confirmed: get(data, 'confirmed') ? true : undefined, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment