首页  >  问答  >  正文

Typescript:来自元组数组的动态列表,没有交集

<p><pre class="brush:php;toolbar:false;">const intents = ["primary", "secondary", "accent", "danger"] as const; const buttonSizes = ["small", "medium", "big"] as const; type IntentType = (typeof intents)[number]; type SizeType = (typeof buttonSizes)[number]; type ButtonProps = { intent?: IntentType; size?: SizeType; } & { [K in IntentType as `${Lowercase<K>}`]?: boolean; };</pre> <p>在这段代码中,我希望 Vue 组件能够接收如下属性 </p> <p>或者 喜欢 </p> <p>now, if I write the code more statically, 喜欢:</p> <pre class="brush:php;toolbar:false;">type ButtonProps = { intent?: "primary" | "secondary" | "accent" | "danger"; size?: "small" | "medium" | "big"; primary?: boolean; secondary?: boolean; accent?: boolean; danger?: boolean; }</pre> <p>它有效......但是我还有一些其他代码需要迭代意图选项,并且只是让它一直重复......</p> <p>第一个示例有效,但由于某种原因 VUE 抛出错误</p> <blockquote> <p>内部服务器错误:[@vue/compiler-sfc] 类型参数传递给 DefineProps() 必须是文字类型或对接口的引用 或文字类型。</p> </blockquote> <p>这个错误似乎是已知的并且正在被解决,所以看起来</p> <p>在不使用交集的情况下更动态地定义 ButtonProps 的其他方法是什么?</p>
P粉163951336P粉163951336414 天前425

全部回复(1)我来回复

  • P粉384244473

    P粉3842444732023-09-01 18:26:56

    鉴于错误显示“引用接口或文字类型”,我假设将 ButtonProps 定义为扩展基本类型的接口应该有效:

    type IntentAndSize = {
      [K in IntentType as `${Lowercase<K>}`]?: boolean;
    };
    
    interface ButtonProps extends IntentAndSize {
      intent?: IntentType;
      size?: SizeType;
    }

    游乐场

    回复
    0
  • 取消回复