如何将接口儿童的类型转换为type []?

时间:2019-06-27 08:16:58

标签: typescript typescript-typings

我有一个接口,我想通过将其子类型转换为type []来生成一个新接口;但我无法实现。如何进行这种转换?

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

2 个答案:

答案 0 :(得分:2)

您快到了。 Mapped type是您要寻找的:

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

Playground

答案 1 :(得分:0)

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

interface IArrayChildrenType<T> {

}

调用

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