You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何扩展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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 20:32:23