B
B
Bone2020-11-09 15:24:31
typescript
Bone, 2020-11-09 15:24:31

How to infer type from interface part with nested structure?

Let's say I have an interface like this:

interface Book {
    id: number,
    author: {
        name: string,
        age: number,
    },
    price: {
        value: number,
        currency: Currency,
    }
}


I want to make a function that will only work with the author field from this interface. Those. the function should expect an object of this type:
function doSomething(author: {name: string, age: number})
How can I automatically infer the type from the Book interface? I tried to do , but as a result I get , but I just need . {name: string, age: number}Pick<Book, "author">{author: {name: string, age: number}}{name: string, age: number}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2020-11-09
@Bone

Book['author']
But if you need different parts of the interface to walk around the program, then it is better to break it into pieces

interface BookAuthor { ... }
interface BookPrice { ... }
interface Book {
  id: number,
  author: BookAuthor,
  price: BookPrice
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question