获取 TypeScript 接口的值。

huangapple go评论83阅读模式
英文:

Get the values of the typescript interface

问题

同事们!

帮我解决以下问题。

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

  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'

请帮助创建类型 Values<T>

以前我通过 enum 解决了这个问题,但在当前情况下无法使用。

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

英文:

colleagues!

Help me to solve the following problem.

There are several interfaces with predefined values. For example:

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

  interface ButtonType {
    readonly Checkout: &#39;CHECKOUT&#39;;
    readonly Pay: &#39;PAY&#39;;
    readonly Simple: &#39;SIMPLE&#39;;
  }

  interface ButtonWidth {
    readonly Auto: &#39;AUTO&#39;;
    readonly Max: &#39;MAX&#39;;
    readonly MaxImportant: &#39;MAX_IMPORTANT&#39;;
  }

I need a wrapper that will create a new type consisting of interface property values. To make it work:

  type Theme = Values&lt;ButtonTheme&gt;; 
  // &#39;BLACK&#39; | &#39;WHITE&#39; | &#39;WHITE-OUTLINED&#39; | &#39;YELLOW&#39;

  type Type = Values&lt;ButtonType&gt;; 
  // &#39;CHECKOUT&#39; | &#39;PAY&#39; | &#39;SIMPLE&#39;

  type Width = Values&lt;ButtonWidth&gt;; 
  // &#39;AUTO&#39; | &#39;MAX&#39; | &#39;MAX_IMPORTANT&#39;

Help to create a type Values<T>, please

Previously I solved this problem via enum, but in the current circumstances it cannot be used.

I found one solution in the documentation, but it refers only to keys, but not to values.

答案1

得分: 1

type Values = T[keyof T];

英文:

As always, there is a fairly simple solution to a complex question:

type Values&lt;T&gt; = T[keyof T];

huangapple
  • 本文由 发表于 2023年7月31日 18:32:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76802756.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定