Typescript:Partial ,具有可选的子属性

问题描述 投票:0回答:1

在打字稿中,是否可以通过Partial<Something>的子属性也都设置为可选的方式,使方法接受Something

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)

非常感谢;)

typescript types conditional-statements partial
1个回答
2
投票

您本质上是在寻找某种深层次的局部映射类型,例如

 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

© www.soinside.com 2019 - 2024. All rights reserved.