最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Typescript - How to assign Partial type to the property of same type of another object? - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 7

It'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

发布评论

评论列表(0)

  1. 暂无评论