Typescript: Partial<MyType> with sub-properties to optional

江枫思渺然 提交于 2021-02-11 14:28:01

问题


Is it possible, in typescript, to let a method accept Partial<Something>, in a way that Something's sub-properties are all set to optional too?

export interface ISomething {
    user: IUser;
}
export interface IUser {
    id: number;
    name: string;
}

export const myMethod = (something: Partial<ISomething>): void => {};

myMethod({ user: { id: 1, name: "" } });   //this works

myMethod({ user: { id: 1 } });             //this doesn't (but I want this to work too)

many thanks ;)


回答1:


You are essentially looking for some sort of deep partial mapped type, something like

 type DeepOptional<T> = T extends object
    ? DeepOptionalObject<T>
    : T | undefined

type DeepOptionalObject<T> = { [P in keyof T]?: DeepOptional<T[P]> }

type Foo = { bar: Bar }
type Bar = { a: number, b: boolean[] }

const f1: Partial<Foo> = { bar: { a: 1 } } // NOPE
const f2: DeepOptional<Foo> = { bar: {a: 1 } } // OK

Playground link



来源:https://stackoverflow.com/questions/60762168/typescript-partialmytype-with-sub-properties-to-optional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!