我的代码中有一些数据,如下所示:

interface Product {
    id: number
    name: string;
}

enum EnumValue {
  'VALUE1' = 'VALUE1',
  'VALUE2' = 'VALUE2',
  'VALUE3' = 'VALUE3',
}

const data = {
  'VALUE1': {
    num1: {id: 1, name: '2'},
    num2: {id: 2, name: '2'},
  },
    'VALUE2': {
    num1: {id: 1, name: '2'},
  },
    'VALUE3': {
    num1: {id: 1, name: '2'},
  },
} as const satisfies { readonly [key in EnumValue]: { [key: string]: Product} };

我需要为我的数据类型定义一个验证器,以便它只 for each EnumValue个属性获取唯一的ID.我是说

data = {
 'VALUE1': {
    num1: {id: 1, name: '2'},
    num2: {id: 1, name: '2'},
  },
    'VALUE2': {
    num1: {id: 1, name: '2'},
  },
    'VALUE3': {
    num1: {id: 1, name: '2'},
  },
}

ts应该抛出错误,因为VALUE1有2个id = 1的对象,但

data = {
 'VALUE1': {
    num1: {id: 1, name: '2'},
    num2: {id: 2, name: '2'},
  },
    'VALUE2': {
    num1: {id: 1, name: '2'},
  },
    'VALUE3': {
    num1: {id: 1, name: '2'},
  },

是有效的值. 我需要as const satisfies个零件来使用我的代码中的数据模型类型. 所以你能帮我定义一个验证器来纠正我的数据类型吗?

有一些代码可以在对象数组上验证唯一ID,这可能会有所帮助,但问题是我不知道如何访问对象值以在类型验证中迭代.link to this question

interface IProduct<Id extends number> {
    id: Id
    name: string;
}

type Validation<
    Products extends IProduct<number>[],
    Accumulator extends IProduct<number>[] = []>
    =
    (Products extends []
        // #1 Last call
        ? Accumulator
        // #2 All calls but last
        : (Products extends [infer Head, ...infer Tail]
            ? (Head extends IProduct<number>
                // #3 Check whether [id] property already exists in our accumulator 
                ? (Head['id'] extends Accumulator[number]['id']
                    ? (Tail extends IProduct<number>[]
                        // #4 [id] property is a duplicate, hence we need to replace it with [never] in order to trigger the error
                        ? Validation<Tail, [...Accumulator, { id: never, name: Head['name'] }]>
                        : 1)
                    // #5 [id] is not a duplicate, hence we can add to our accumulator whole product
                    : (Tail extends IProduct<number>[]
                        ? Validation<Tail, [...Accumulator, Head]>
                        : 2)
                )
                : 3)
            : Products)
    )

推荐答案

Tnx to@jcalz这个问题已经得到回答.该解决方案在this link年内实施

Javascript相关问答推荐

如何为GrapesJS模板编辑器创建自定义撤销/重复按钮?

如何判断属于多个元素的属性是否具有多个值之一

从实时数据库(Firebase)上的子类别读取数据

fs. writeFile()vs fs.writeFile()vs fs.appendFile()

Snowflake JavaScript存储过程返回成功,尽管预期失败

我们如何从一个行动中分派行动

引用在HTMLAttributes<;HTMLDivElement>;中不可用

如何添加绘图条形图图例单击角形事件

TypeError:无法分解';React2.useContext(...)';的属性';basename';,因为它为空

如何在Angular拖放组件中同步数组?

覆盖加载器页面避免对页面上的元素进行操作

SPAN不会在点击时关闭模式,尽管它们可以发送日志(log)等

使用类型:assets资源 /资源&时,webpack的配置对象&无效

Django导入问题,无法导入我的应用程序,但我已在设置中安装了它

是否可以在不更改组件标识的情况下换出Reaction组件定义(以维护状态/引用等)?如果是这样的话,是如何做到的呢?

我在哪里添加过滤器值到这个函数?

rxjs在每次迭代后更新数组的可观察值

如何在函数组件中保留对计时器的引用

如何动态呈现适合未知屏幕大小的最大数量的表行?苗条的

JavaScript structuredClone在Chrome/Edge中获得了非法调用,但在NodeJS中没有