简体   繁体   中英

Typescript Pick multiple keys

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'> Pick<A, 'a'| 'b'> can't work as expected

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)

You might be over complicating this.

How about..

interface A{
  a:{
    name: string
  }
  b:{
    age: number
  }
}

const child: A['a' | 'b']= {
  name: 'mike',
  age: 18
}

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

It already supports multiple keys

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
 
type TodoPreview = Pick<Todo, "title" | "completed">;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM