Essential TypeScript Tips
TypeScript Tips for Better Code
Let’s explore some TypeScript features that can make your code more robust.
Generic Constraints
Here’s how to use generic constraints effectively:
interface HasLength {
length: number;
}
function logLength<T extends HasLength>(arg: T): number {
console.log(arg.length);
return arg.length;
}
// Works with strings
logLength("Hello"); // 5
// Works with arrays
logLength([1, 2, 3]); // 3
// Error: number doesn't have length
logLength(123); // Error!
Utility Types
TypeScript provides powerful utility types:
interface User {
id: number;
name: string;
email: string;
password: string;
}
// Only pick certain fields
type PublicUser = Pick<User, 'id' | 'name'>;
// Make all fields optional
type PartialUser = Partial<User>;
// Make all fields required
type RequiredUser = Required<User>;