本文介绍了打字稿:Partial< MyType>带有可选的子属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在打字稿中是否有可能让方法接受 Partial< Something>
,从而将 Something
的子属性也全部设置为可选?
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)
非常感谢;)
推荐答案
您本质上是在寻找某种深层次的部分映射类型,例如
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
这篇关于打字稿:Partial< MyType>带有可选的子属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!