I'm writing Unit Test cases for which I need very limited properties from the objects.
Now there is one case in which I assign a Partial object to another object's property of T type. But TS errors out that I can't assign Partial to the T type, which I understand should be the case.
But then how am I supposed to assign the object.
Below is the sample example I'm trying to solve.
const a: Partial<A> = {
a1: "my a1 prop"
};
const b: Partial<B> = {
b1: "my b1 prop",
b2: a,
}
// A: {a1: string, a2: string, a3: string}
// B: {b1: string, b2: A, b3: string}
So, here I want to assign the "a" object to the "b2" property without creating the whole "a" object.
Now, the Partial makes the b2 property optional but it doesn't make all the nested properties optional as well.
So, is there any way for me to achieve this assignment without creating the whole "a" object first?
I'm writing Unit Test cases for which I need very limited properties from the objects.
Now there is one case in which I assign a Partial object to another object's property of T type. But TS errors out that I can't assign Partial to the T type, which I understand should be the case.
But then how am I supposed to assign the object.
Below is the sample example I'm trying to solve.
const a: Partial<A> = {
a1: "my a1 prop"
};
const b: Partial<B> = {
b1: "my b1 prop",
b2: a,
}
// A: {a1: string, a2: string, a3: string}
// B: {b1: string, b2: A, b3: string}
So, here I want to assign the "a" object to the "b2" property without creating the whole "a" object.
Now, the Partial makes the b2 property optional but it doesn't make all the nested properties optional as well.
So, is there any way for me to achieve this assignment without creating the whole "a" object first?
Share Improve this question asked Jun 23, 2020 at 14:18 VishalVishal 1752 silver badges11 bronze badges2 Answers
Reset to default 7It's likely you want a DeepPartial
which is like Partial
but recurses down through properties. You can define it like this:
type DeepPartial<T> = { [K in keyof T]?: DeepPartial<T[K]> }
And then use it instead of Partial
:
const a: DeepPartial<A> = {
a1: "my a1 prop"
};
const b: DeepPartial<B> = {
b1: "my b1 prop",
b2: a
} // okay
Does that meet your needs? Hope it helps; good luck!
Playground link to code
You can set type b2
as Partial
:
type A = { a1: string; a2: string; a3: string };
type B = { b1: string; b2: A; b3: string };
type B1 = { b1: string; b2: Partial<A>; b3: string };
Or use DeepPartial
type DeepPartial<T> = T extends Function ? T : T extends object ? { [P in keyof T]?: DeepPartial<T[P]> } : T;
type B2 = DeepPartial<B>;
Playground