TS会创建描述性较低的.d.ts文件

时间:2018-06-23 01:30:19

标签: node.js typescript typescript2.0 tsc

我在.ts文件中输入了以下内容:

export const OverSizedItems = <{ [key: string]: OverSizedItemType }>{

  NONE: {
    factor: 1,
    count: 0,
    mooversNeeded: 1,
  },

  ONE: {
    factor: 1.01,
    count: 1,
    mooversNeeded: 4,
  },

  TWO: {
    factor: 1.03,
    count: 2,
    mooversNeeded: 4,
  },

  THREE_PLUS: {
    factor: 1.07,
    count: 5,
    mooversNeeded: 6,
  }

};

它转换为:

export declare const OverSizedItems: {
    [key: string]: OverSizedItemType;
};

但是如果改变原始格式,而忽略了索引签名类型信息,我会得到这个,这正是我想要的:

export declare const OverSizedItems: {
    NONE: {
        factor: number;
        count: number;
        mooversNeeded: number;
    };
    ONE: {
        factor: number;
        count: number;
        mooversNeeded: number;
    };
    TWO: {
        factor: number;
        count: number;
        mooversNeeded: number;
    };
    THREE_PLUS: {
        factor: number;
        count: number;
        mooversNeeded: number;
    };

};

枚举在这里不起作用,因为枚举不能指向对象。

那我该怎么做才能添加索引签名但保留所有值呢?

1 个答案:

答案 0 :(得分:1)

我能想到的最好的方法是使用Record类型,将所有键写成一个并集,就像这样:

type OverSizedItemKey = "NONE" | "ONE" | "TWO" | "THREE_PLUS"

export const OversizedItems: Record<OverSizedItemKey, OverSizedItemType> = {
  // ...
}

Record使用mapped type,因此请确保您熟悉它,以了解其工作原理/原因。