Answer the question
In order to leave comments, you need to log in
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
You are getting an error because your code is invalid.
Let's figure it out in order.
You describe a type one
as an object with two required fields: items
and item
Then you describe a second type two
as an object with two required fields: select
and data
Then you say to yourself: "This function must return either type one
or 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'> {
}
i have two big interfacesYour main mistake in this, interfaces should be minimal and describe the minimum that is required in a particular place.
{select: string}
and/or{items: number[]}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question