如何扩展RemoveNull类型助手以移除嵌套数组中的null值?
如何递归移除嵌套数组中对象属性的null值?
我有如下TypeScript接口:
interface SubBarText { text: string; } interface BarText { text: string; subBar?: SubBarText[] | null; } export interface Foo { bar: BarText[] | null; baz: { subBaz: string | null }; boof: string; }
我希望生成一个新类型,移除所有属性中的null值。我找到一个可递归移除对象及嵌套对象属性中null值的单行类型工具:
export type RemoveNull<Ob> = { [K in keyof Ob]: Ob[K] extends object ? RemoveNull<Ob[K]> : NonNullable<Ob[K]> };
但这个类型无法处理嵌套数组(比如bar)中的对象属性的null值:
- 当
bar本身为null时,它能正确触发类型错误:
const CorrectlyFails: RemoveNull<Foo> = { bar: null, baz: { subBaz: null }, boof: null }
- 但它无法检测到
subBar中的null值:
const shouldFailButDoesNot: RemoveNull<Foo> = { bar: [ { text: 'asdf', subBar: null // <-- 此处本应报错但未报错 } ], baz: { subBaz: null }, // <-- 此处正确触发报错 boof: null // <-- 此处正确触发报错 }
我可以通过手动构造类型解决这个问题:
const CorrectlyFails2: Omit<RemoveNull<Foo>, "bar"> & { bar: RemoveNull<BarText[]> } = { bar: [ { text: 'asdf', subBar: null } ], baz: { subBaz: null }, boof: null }
但我希望找到一种方法,扩展RemoveNull类型以自动处理类似bar这样的嵌套数组场景。
内容的提问来源于stack exchange,提问作者nvioli
相关产品推荐
相关产品推荐

