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

如何在TypeScript中限制overrides的键与components数组项匹配?

实现方案

要让overrides的键严格匹配components数组中的元素,你可以通过泛型+映射类型来实现,核心思路是让TypeScript捕获components数组的具体字符串字面量类型,再用这个类型约束overrides的键。

步骤1:定义泛型接口

将原接口改为泛型形式,用泛型参数约束组件名称的类型:

interface MyJsonObject<T extends string> {
    components: T[];
    overrides: {
        // 仅允许T中的字符串作为键,可选属性适配可能没有覆盖的情况
        [K in T]?: {
             [propName: string]: unknown;
        };
    };
}

步骤2:用辅助函数自动推导类型

直接使用泛型接口需要手动指定类型参数,不够便捷。可以写一个辅助函数让TypeScript自动从components数组推导字面量类型:

function createConfig<T extends string>(config: MyJsonObject<T>) {
    return config;
}

验证效果

合法示例(无报错)

const validConfig = createConfig({
    components: ['test'],
    overrides: {
        test: {
            foo: 'bar',
        }
    }
});

非法示例(TypeScript报错)

当overrides的键不在components中时,TypeScript会直接提示错误:

// 错误提示:对象字面量只能指定已知属性,"baz"不在类型"{ test?: { [propName: string]: unknown; } | undefined; }"中
const invalidConfig = createConfig({
    components: ['test'],
    overrides: {
        baz: {
            foo: 'bar',
        }
    }
});

补充:手动指定泛型的方式

如果不需要辅助函数,也可以手动指定泛型参数,但需要明确写出组件名称:

const config: MyJsonObject<'test'> = {
    components: ['test'],
    overrides: {
        test: { foo: 'bar' }
    }
};

内容的提问来源于stack exchange,提问作者charmeleon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 02:12:40