Home > Software design >  Typescript array of generic types
Typescript array of generic types

Time:12-11

I want to do something like this:

type Item<T> = T & {
  func: (v: T) => void
}

function a<What>(...items: Item<What>[]) {}

a({
  name: "",
  func: (v: {name: string}) => {}
}, {
  count: 0,
  func: (v: {count: number}) => {}
})

However above code will cause an error, how to do the similar thing with typscript?

CodePudding user response:

I almost have it, however i cant get function to infer the generic on its own, but im sharing this anyway, in case someone else might solve it, or in case this helps you nontheless.

The trick i used to is to recursively infer each Item of What, that way What is properly handled as tuple and the Item constraint is applied to each element in What seperately.

type Item<T> =
    T & {func(v:T):void}

type Items<What> =
    What extends [Item<infer A>, ...infer Rest]
    ? [Item<A>,...Items<[...Rest]>]
    : What extends [] ? [] : never

function testFunction<What>(...items: Items<What>) {}

//this works, with an explicit generic
testFunction<[Item<{
    name: string;
}>, Item<{
    count: number;
}>]>({
  name: "",
  func: (v: {name: string}) => {}
}, {
  count: 0,
  func: (v: {count: number}) => {}
})

Playground

CodePudding user response:

type Item<T> = T & {
  func: (v: T) => void
}

function a<A extends Item<any>[]>(...items: A) {}

a({
  name: "",
  func: (v: {name: string}) => {}
}, {
  count: 0,
  func: (v: {count: number}) => {}
})
// ^?
// function a<[{
//     name: string;
//     func: (v: {
//         name: string;
//     }) => void;
// }, {
//     count: number;
//     func: (v: {
//         count: number;
//     }) => void;
// }]>(items_0: {
//     name: string;
//     func: (v: {
//         name: string;
//     }) => void;
// }, items_1: {
//     count: number;
//     func: (v: {
//         count: number;
//     }) => void;
// }): void
  • Related