Using the Pick
method can efficiently select specific fields from a type without needing to define a separate mapped type. It allows for selecting multiple fields at once:
interface A {
a1: { a11: string };
a2: { a21: string };
a3: { a31: string };
}
// Pick<A, "a1" | "a2"> <=> { a1: { a11: string }, a2: { a21: string } }
let var1: Pick<A, "a1" | "a2"> = { a1: { a11: "Hello" }, a2: { a21: "World" } };
If you frequently need to pick from type A
, it's possible to create a dedicated type while maintaining flexibility with a single key parameter:
type B<TKey extends keyof A> = Pick<A, TKey>
let var1: B<"a1" | "a2"> = { a1: { a11: "Hello" }, a2: { a21: "World" } };
When working with types, it is recommended to utilize built-in methods like Pick
instead of creating new mapped types. This simplifies understanding for team members as built-in methods are well-documented and easier to grasp.
It's important to note that the B
type does not restrict users to picking only two fields from A</code. By using <code>never
and unions, any number of keys can be selected from
A</code:</p>
<pre><code>// pick 2 fields
let var1: B<"a1", "a2"> = { a1: { a11: "Hello" }, a2: { a21: "World" } };
// pick 1 field
let var2: B<"a1", never> = { a1: { a11: "Hello" } };
// pick all 3
let var3: B<"a1" | "a2", "a3"> = { a1: { a11: "Hello" }, a2: { a21: "World" }, a3: { a31: "World" } };