获取TypeScript接口的值

问题描述 投票:0回答:1

同事们!

帮我解决以下问题。

有几个带有预定义值的接口。例如:

  interface ButtonTheme {
    readonly Black: 'BLACK';
    readonly White: 'WHITE';
    readonly WhiteOutlined: 'WHITE-OUTLINED';
    readonly Yellow: 'YELLOW';
  }

  interface ButtonType {
    readonly Checkout: 'CHECKOUT';
    readonly Pay: 'PAY';
    readonly Simple: 'SIMPLE';
  }

  interface ButtonWidth {
    readonly Auto: 'AUTO';
    readonly Max: 'MAX';
    readonly MaxImportant: 'MAX_IMPORTANT';
  }

我需要一个包装器来创建一个由接口属性值组成的新类型。为了让它发挥作用:

  type Theme = Values<ButtonTheme>; 
  // 'BLACK' | 'WHITE' | 'WHITE-OUTLINED' | 'YELLOW'

  type Type = Values<ButtonType>; 
  // 'CHECKOUT' | 'PAY' | 'SIMPLE'

  type Width = Values<ButtonWidth>; 
  // 'AUTO' | 'MAX' | 'MAX_IMPORTANT'

请帮助创建类型值

之前我通过

enum
解决了这个问题,但目前情况下无法使用。

我在文档中找到了一种解决方案,但它仅涉及键,而不涉及值。

typescript interface
1个回答
0
投票

一如既往,对于复杂的问题有一个相当简单的解决方案:

type Values<T> = T[keyof T];
© www.soinside.com 2019 - 2024. All rights reserved.