类型 struct 为 示例:

type TFiltersTypes = 'selectableTags' | 'dropdown';

type TSelectableTabsFilterItem = {
    id: string;
    label: string;
    isSelected: boolean;
};

type TFilter = {
    type: TFiltersTypes;
    label: TLocalesKey;
    data: (TFiltersTypes extends 'selectableTags'
        ? TSelectableTabsFilterItem
        : TDropdownFilterItem)[];
};

type TDropdownFilterItem = {
    id: string;
    label: string;
    Icon: string;
    isSelected: boolean;
};

type TFilterProps = {
    data: TFilter[];
};

const data = [
    {
        type: 'selectableTags',
        label: 'filters.mediaType.label',
// Property 'Icon' is missing in type '{ id: string; label: string; isSelected: true; }' but required 
// in type 'TDropdownFilterItem'.(2741)
// TSelectableTabsFilterItem
        data: [
            {
                id: '1',
                label: '12',
                isSelected: true,
            },
            {
                id: '2',
                label: '1',
                isSelected: false,
            },
            {
                id: '3',
                label: '1',
                isSelected: false,
            },
        ],
    },
    {
        type: 'dropdown',
        label: 'filters.services.label',
        data: [
// TDropdownFilterItem 
            {
                id: '1',
                label: '1',
                Icon: '',
                isSelected: true,
            },
        ],
    },
] satisfies TFilter[];

现在我有一个错误 Property 'Icon' is missing in type '{ id: string; label: string; isSelected: true; }' but required in type 'TDropdownFilterItem'.有没有可能创造出一些有效的东西?我希望有灵活的类型的数组与不同的对象类型取决于对象ID

推荐答案

您希望TFilterdiscriminated union,其中每个联合成员都有不同的type/data属性类型对.就像这样:

type TFilter = {
    type: 'selectableTags',
    label: string,
    data: TSelectableTabsFilterItem[]
} | {
    type: 'dropdown';
    label: string;
    data: TDropdownFilterItem[];
};

该示例代码不起作用,因为TFiltersTypes只是一个特定类型,因此conditional typeTFiltersTypes extends 'selectableTags' ? TSelectableTabsFilterItem : TDropdownFilterItem被Eager 地计算为仅TDropdownFilterItem.如果TFiltersTypesgeneric类型参数,那么您将能够使用条件类型来像那样打开它,但它仍然没有用处,因为TFilter需要是像TFilter<T extends TFiltersTypes>这样的泛型类型.无论如何,最好的情况是最终会产生一个受歧视的unions ,所以这就是你从一开始就应该做的.

Playground link to code

Node.js相关问答推荐

运行JEST测试时找不到模块&q;错误

如何从基于JSON的HTML/SCSS模板生成PDF?

EJS ForEach循环标记

创建查询以展开数组并筛选出具有特定值的元素之后的元素

无法生成仅具有生产依赖项的 node 类型脚本项目

使用AWS SDK for JavaScript V3将图像从node.js上传到s3 bucket

如何修复node.js中的错误代码无法加载资源:服务器响应状态为403(禁止)

当其中一个端点不工作时,如何使用 axios.all() 调用多个 API?

为什么我的react 表单不能正常工作?

如何在 TypeScript 中输出 Hackerrank 二叉树问题?

cURL 和 shell 任务

安全沙箱并执行用户提交的 JavaScript?

Dart 语言比 JavaScript (Node.js) 有什么好处

AngularJS +sails.js

代理后面的凉亭

npm package.json 操作系统特定脚本

遍历 NodeJS 中的一系列日期

需要 node-gyp 的 npm install 在 Windows 上失败

Route.get() 需要回调函数,但得到对象未定义

从 node.js 连接到 mongodb 时出现 ECONNREFUSED 错误