Oct 26, 2023 Sage 1 min read
TypeScript Tricks I Love
#typescript#frontend#coding
TypeScript has a few utility types that I find myself using in almost every project.
Partial and Pick
Sometimes you only want a subset of a type.
typescriptinterface User { id: string; name: string; email: string; role: 'admin' | 'user'; } // Only need id and email for this function function sendEmail(user: Pick<User, 'id' | 'email'>) { console.log(`Sending to ${user.email}`); }
Advanced Generic Constraints
You can enforce that a generic type must have certain properties.
typescriptfunction getKey<T extends object, K extends keyof T>(obj: T, key: K) { return obj[key]; } const user = { name: "Sage", age: 30 }; const name = getKey(user, "name"); // Valid // const fail = getKey(user, "address"); // Error: Argument of type '"address"' is not assignable...