TypeScript: deep partial?

前端 未结 2 1034
没有蜡笔的小新
没有蜡笔的小新 2020-12-20 11:48

Is there a way to specify a partial type in TypeScript that also makes all child objects partials as well? For example:



        
相关标签:
2条回答
  • 2020-12-20 12:05

    If you're looking for a quick and easy solution, check out the type-fest package, which has many useful prebuilt TypeScript types including the PartialDeep type.

    For a more technical and customizable solution, see this answer.

    0 讨论(0)
  • You can simply create a new type, say, DeepPartial, which basically references itself:

    type DeepPartial<T> = {
        [P in keyof T]?: DeepPartial<T[P]>;
    };
    

    Then, you can use it as such:

    const foobar: DeepPartial<Foobar> = {
      foo: 1,
      bar: { baz: true }
    };
    

    See proof-of-concept example on TypeScript Playground.

    0 讨论(0)
提交回复
热议问题