Skip to content

Instantly share code, notes, and snippets.

@justsml
Created September 8, 2023 04:11
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 justsml/8d2e80c974abe3ee244e8dd54638cab4 to your computer and use it in GitHub Desktop.
Save justsml/8d2e80c974abe3ee244e8dd54638cab4 to your computer and use it in GitHub Desktop.
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