Home > OS >  how to make a type which only extracts property values from the interface in typescript?
how to make a type which only extracts property values from the interface in typescript?

Time:01-14

I exactly don't know how to express my intention in a single sentence, so I will try my best.

interface A {
  person: {
    name: string;
    age: number;
  },
  count: number
}

type B = Pick<A, 'person'>

// type B = {person: {name: string; age: number;}}

As we can see, if we use Pick utility type, type B has a key person.

What if I want to get rid of the key(person), and only want to have those property values like below type C?

 // type C which I want to make.
 type C = {
   name: string;
   age: number;
 }

 // something like StripKeyOut<Pick<A, 'person'>> is possible?

appreciate in advance for your help.

CodePudding user response:

Typescript has Indexed Access Types: type B = A['person']

Playground

CodePudding user response:

I don't know if there is a way to do exactly what you described but you can do the following. You can create separate interface for the person object so your code would look like this.

interface A {
  person: Person,
  count: number
}

interface Person {
  name: string;
  age: number;
}

I believe that would be the best practice.

  • Related