Advanced TypeScript #2: Omit/Pick from type
Here’s part 2 of 7 of the Advanced TypeScript series, where I share TypeScript patterns I’ve encountered in enterprise grade applications.
Tips 3 to 7 (or maybe even more by then) will come in September.
2. Omit/Pick from Object
"Removing" or "selecting" fields from an object is quite widespread by this point but very useful.
import { expectTypeOf } from 'expect-type';
export type Product = {
price: number;
description: string;
};
export type Cart = {
lineItems: {
product: Product;
amount: number;
};
total: number;
};
expectTypeOf<Pick<Cart, 'total'>>().toEqualTypeOf<{ total: number }>();
expectTypeOf<Omit<Cart['lineItems'], 'amount'>>().toEqualTypeOf<{
product: Product;
}>();
Why would you want to do this? It reduces copy-paste and keeps the copies synced. Due to the way TypeScript type-checks the structure/contents (2 types with the same content may as well be the same type as far as TypeScript is concerned), there aren't really other disadvantages.
That's this week's pattern, you can get a sneak peek of the rest at codewithhugo.com/typescript-types-in-the-trenches/, or access the annotated source at github.com/HugoDF/real-world-ts.