Home > Enterprise >  Record type where values are the same as a defined interface but as an array
Record type where values are the same as a defined interface but as an array

Time:09-21

I have an interface where all properties have a base type:

interface Types {
    a: number,
    b: string,
    c: boolean
}

And I would like to have a Database type which looks the same as the Types interface, but with types as arrays instead of base types.

Like this (it's just a representation, as this will be a constructed type):

{
    a: number[],
    b: string[],
    c: boolean[]
}

What I tried is:

type Database<Key extends keyof Types> = Record<Key, Array<Types[Key]>>

I thought the generic type would be a "silent type" but I actually have to give it as an argument when I want to use the Database type... and that's not what I want.

I would like the Database type to be usable as is.


Solution:

interface Types {
    a: number,
    b: string,
    c: boolean
}

type ValueToArray<T> = {
  [K in keyof T]: Array<T[K]>;
};

type Database = ValueToArray<Types>;

CodePudding user response:

Use mapped types

type ValueToArray<T> = {
  [K in keyof T]: Array<T[K]>;
};
  • Related