Typescript:来自元组数组的动态列表,没有交集
P粉163951336
P粉163951336 2023-08-31 23:02:45
[Vue.js讨论组]
<p><pre class="brush:php;toolbar:false;">const intents = [&quot;primary&quot;, &quot;secondary&quot;, &quot;accent&quot;, &quot;danger&quot;] as const; const buttonSizes = [&quot;small&quot;, &quot;medium&quot;, &quot;big&quot;] as const; type IntentType = (typeof intents)[number]; type SizeType = (typeof buttonSizes)[number]; type ButtonProps = { intent?: IntentType; size?: SizeType; } &amp; { [K in IntentType as `${Lowercase&lt;K&gt;}`]?: 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?: &quot;primary&quot; | &quot;secondary&quot; | &quot;accent&quot; | &quot;danger&quot;; size?: &quot;small&quot; | &quot;medium&quot; | &quot;big&quot;; 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粉163951336
P粉163951336

全部回复(1)
P粉384244473

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

type IntentAndSize = {
  [K in IntentType as `${Lowercase<K>}`]?: boolean;
};

interface ButtonProps extends IntentAndSize {
  intent?: IntentType;
  size?: SizeType;
}

游乐场

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号