Reputation: 211
interface A{
a:{
name: string
}
b:{
age: number
}
}
type PickMultiple = ..... //todo
const child:PickMultiple<A,['a','b']> = {
name: 'mike',
age: 18
}
How can I extract multiple keys? it was same as Pick Child key
Ofcourse Pick<A, 'a'| 'b'>
can't work as expected
Upvotes: 12
Views: 19542
Reputation: 24201
You might be over complicating this.
Update:
Like pointed out in the comments by ' Sebastien H', my original answer was not totally correct, it was basically saying a or b, and due to duck typing having both works too. So to make this stricter you need intersection type, not a union type.
How about..
interface A{
a:{
name: string
}
b:{
age: number
}
}
const child: A['a'] & A['b']= {
name: 'Mike',
age: 23,
}
With the original A['a' | 'b']
it would allow either name or age to be left out.
ps. Doing A['a' & 'b']
would also not be a shortcut here.
Upvotes: 3
Reputation: 4915
You can actually pick multiple keys by default
interface A {
a: {
name: string;
};
b: {
age: number;
};
}
type Picked = Pick<A, 'a' | 'b'>;
See full documentation: https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys
Upvotes: 4
Reputation: 211
interface A {
a: {
name: string
}
b: {
age: number
}
}
type Picked<T, K extends keyof T> = T[K]
const a: Picked<A, 'a' | 'b'> = {
name: '1',
age: 18,
}
console.log(a)
Upvotes: 9
Reputation: 211
It already supports multiple keys
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
Upvotes: 21