Skip to content

Instantly share code, notes, and snippets.

@jsjoeio
Created July 4, 2021 18:37
Show Gist options
  • Save jsjoeio/e62f668dc910ec3eb331570023d35d57 to your computer and use it in GitHub Desktop.
Save jsjoeio/e62f668dc910ec3eb331570023d35d57 to your computer and use it in GitHub Desktop.
TypeScript - Pick utility-type real-world example
export type User = {
/** Unix timestamp - created at time of write */
timestamp: number
/** ID of the user - created at time of write */
id: string
telegramUsername: string
telegramUserId: string
/** Like a nickname */
preferredName: string
firstName: string
lastName: string
timezone: string
twitterHandle: string
stripeCustomerId: string
/** IDs the user is in - comma separated string */
groupIds: string
}
// Using a serverless function with Vercel's /api routes
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === "POST") {
try {
const {
telegramUsername,
preferredName,
timezone,
twitterHandle,
stripeCustomerId,
groupIds,
}: Pick<
User,
| "telegramUsername"
| "preferredName"
| "timezone"
| "twitterHandle"
| "stripeCustomerId"
| "groupIds"
> = req.body
const user: User = {
timestamp: Date.now(),
id: uuidv4(),
telegramUsername,
preferredName,
timezone,
twitterHandle,
stripeCustomerId,
groupIds,
firstName: "",
lastName: "",
telegramUserId: "",
}
await writeUserToDatabase(user)
res.status(200).json({ success: true })
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message })
}
}
}
// Read more here: https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment