具有独特属性的 TypeScript 对象集

Szw*_*r16 4 javascript set typescript

我简单地写了这样的接口:

interface IProduct {
  id: number;
  name: string;
  price: number;
  description?: string;
}
Run Code Online (Sandbox Code Playgroud)

现在我想id在 ReadonlyArray 中保持唯一。因此,当创建一些产品时,我想防止添加具有相同 id 的对象。包含产品的数组将在文件中创建一次,并且不会被修改。

你对此有什么想法吗?JS Set 将是一个很好的解决方案,但我无法向它们添加自己的比较器。请不要提供需要额外框架等的解决方案。

cap*_*ian 5

此示例使用类型系统来静态验证是否存在重复项。


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

const product = <Id extends number>(id: Id, name: string) => ({ id, name })

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'] }]>
                        : never)
                    // #5 [id] is not a duplicate, hence we can add to our accumulator whole product
                    : (Tail extends IProduct<number>[]
                        ? Validation<Tail, [...Accumulator, Head]>
                        : never)
                )
                : never)
            : never)
    )

type Ok = Validation<[{ id: 1, name: '1' }, { id: 2, name: '2' }]>
type Fail = Validation<[{ id: 1, name: '1' }, { id: 1, name: '2' }]> // id:never

const builder = <
    Product extends IProduct<number>,
    Products extends Product[]
>(...products: [...Products] & Validation<Products>) => products

builder(product(1, 'John'), product(2, 'Doe'))
Run Code Online (Sandbox Code Playgroud)

操场

Validation- 递归地迭代所有传递到函数产品中的内容。如果product[id]累加器类型中已存在 - 将id属性替换为never,否则只需将乘积添加到累加器中。

请看评论#1#2......

如果您不想使用rest运算符,请考虑以下示例:


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

const product = <Id extends number>(id: Id, name: string) => ({ id, name })

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)
    )


type Ok = Validation<[{ id: 1, name: '1' }, { id: 2, name: '2' }]>
type Fail = Validation<[{ id: 1, name: '1' }, { id: 1, name: '2' }]> // id:never

const builder = <
    Id extends number,
    Product extends IProduct<Id>,
    Products extends Product[]
>(products: Validation<[...Products]>) => products

builder([product(1, 'John'), product(1, 'John')]) // error
Run Code Online (Sandbox Code Playgroud)

操场

如果你对静态验证感兴趣,可以查看我的文章