L
L
Levingstone2020-08-30 17:13:25
typescript
Levingstone, 2020-08-30 17:13:25

How to assign a class/object two different interfaces with some common types?

Let's say I have two large interfaces and I want to make one interface complement the other. Is it possible without decomposing each interface into smaller ones and not making the type optional via `?` ?

In reality, interfaces can be much larger, dozens of types each, but here is a conditional example that will give such an error

Type '{ select: string; items: number[]; }' is not assignable to type 'one | two'. Property 'data' is missing in type '{ select: string; items: number[]; }' but required in type 'two'


interface one {
    items: number[],
    item: string
}

interface two {
    select: string,
    data: object,
}


function g(): one | two {
    const items = [1];
    const select = '';
    return {
        select,
        items
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2020-08-30
@Levingstone

You are getting an error because your code is invalid.
Let's figure it out in order.
You describe a type oneas an object with two required fields: itemsand item
Then you describe a second type twoas an object with two required fields: selectand data
Then you say to yourself: "This function must return either type oneor type two. Either this or that . ". And you describe a function that returns neither one nor the other.
If not atomic types but some subsets can walk around your program - Do decomposition
This will help you.
For those cases when you have a function that generates some piece of an atomic type, you can describe it using Pick
. And at worst, if you are really itching to code it, you can write it like this:

function g(): Pick<one, 'items'> & Pick<two, 'select'> {

}

D
Dmitry Belyaev, 2020-08-30
@bingo347

i have two big interfaces
Your main mistake in this, interfaces should be minimal and describe the minimum that is required in a particular place.
https://www.typescriptlang.org/docs/handbook/union...
Read about unions, they work completely differently than you plan.
And finally, typescript has structural typing and it infers types quite well in many places. In your example, ts is quite capable of calculating the return type, and it will fit wherever required {select: string}and/or{items: number[]}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question