【问题标题】:Type representing a tuple type with the keys of an object as string literals表示元组类型的类型,对象的键为字符串文字
【发布时间】:2017-07-21 22:00:45
【问题描述】:

给定一个接口:

interface EPostageInsertExEvent_Parameter {
    readonly Doc: Word.Document;
    cpDeliveryAddrStart: number;
    cpDeliveryAddrEnd: number;
    readonly cpReturnAddrStart: number,
    readonly cpReturnAddrEnd: number;
    readonly xaWidth: number;
    readonly yaHeight: number;
    readonly bstrPrinterName: string;
    readonly bstrPaperFeed: string;
    readonly fPrint: boolean;
    fCancel: boolean;
}

如何将由该接口的键组成的元组类型定义为字符串文字?换句话说,相当于以下内容:

type EPostageInsertExEvent_ArgNames = ['Doc', 'cpDeliveryAddrStart', 'cpDeliveryAddrEnd',
    'cpReturnAddrStart', 'cpReturnAddrEnd', 'xaWidth', 'yaHeight', 'bstrPrinterName',
    'bstrPaperFeed', 'fPrint', 'fCancel'];

【问题讨论】:

  • 你想要一个元组还是一个字符串数组?您想要在设计或运行时使用它?
  • @RodrigoPedrosa 类型应该是元组类型,由字符串文字组成。我想要它在设计时。
  • 我想你已经在你的问题中做到了。
  • @RodrigoPedrosa,这个想法不是自己写出来的。请参阅下面的答案。

标签: typescript


【解决方案1】:

目前这在 TypeScript 中是不可能的。 GitHub 中有一个feature request 允许这样做,但那里没有太多动静。 (你可能想给它一个 ? 并描述你的用例,或者你可能不会。)TypeScript 还没有对类型函数的广泛支持。现在你能得到的最接近的是:

type EPostageInsertExEvent_ArgNames = Array<keyof EPostageInsertExEvent_Parameter>;

但这并不能保证密钥的存在性、唯一性或顺序。很抱歉没有更好的消息。

【讨论】:

    猜你喜欢
    • 2018-12-12
    • 2021-08-02
    • 2020-09-11
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多