马邦德
马邦德

Reputation: 103

How to transform interface children's type to type[]?

I got an interface, and I want to generate an new interface by transforming it's children's type into type[]; But I cannot fulfill it. How to do this transformation?

interface IItem {
  a: number;
  b: number;
  c: string;
}

interface IArrayChildrenType<T> {
  // I tried this way, but it was totally incorrect
  // [key: keyof T]: Array<typeof T[key]>;
}

interface IExpected {
  a: number[];
  b: number[];
  c: string[];
}

type INewType = IArrayChildrenType<IItem>;

// expect INewType === IExpected

Upvotes: 0

Views: 41

Answers (2)

Chanaka Weerasinghe
Chanaka Weerasinghe

Reputation: 5742

interface IItem {
  a: number;
  b: number;
  c: string;
  childrentype: [IArrayChildrenType<T>]
}

interface IArrayChildrenType<T> {

}

calling it

const IItem: item
const children: IArrayChildrenType<T>  = values[1]
item.childrentype = children  

Upvotes: 0

Aleksey L.
Aleksey L.

Reputation: 37938

You're almost there. Mapped type is what you're looking for:

type IArrayChildrenType<T> = {
    [P in keyof T]: Array<T[P]>;
}

Playground

Upvotes: 2

Related Questions