uniapp x中defineProps能用自定义类型吗

uniapp x中defineProps能用自定义类型吗


<code class="language-javascript">
&lt;script setup&gt;  
import { Msg } from '@/model/chat.uts'  

interface Props {  
  msg : Msg,  
  msgId : String  
}  
const props = defineProps&lt;Props&gt;()
</code>
这样h5能运行起来,但安卓报错

<code class="language-javascript">
:05:15.483          x Expression expected  
09:05:15.483            at components/message-list/message-bubble.uvue:10:1  
09:05:15.483          7 |     __name: 'message-bubble',  
09:05:15.483          8 |     __props: Props,  
09:05:15.483          9 |     props: {  
09:05:15.483         10 |         msg: { type: [Object as PropType&lt;id&gt;, String,  &gt; , Object as PropType&lt;avatar&gt;, String,  &gt; , Object as PropType&lt;atUserList&gt;, Array&lt;String&gt;,  &gt; , Object as PropType&lt;conversationID&gt;, String,  &gt; , Object as PropType&lt;conversationType&gt;, String,  &gt; , Object as PropType&lt;flow&gt;, String,  &gt; , Object as PropType&lt;from&gt;, String,  &gt; , Object as PropType&lt;nick&gt;, String,  &gt; , Object as PropType&lt;to&gt;, String &gt; , Object as PropType&lt;type&gt;, String &gt; , Object as PropType&lt;time&gt;, Number &gt; , Object as PropType&lt;text&gt;, MsgText &gt; ], required: true },
</code>

1 回复

在 uni-app x 中,defineProps 目前不支持直接使用 TypeScript 接口或自定义类型作为泛型参数。虽然 H5 端可能能够运行,但在原生平台(如 Android)上会编译失败。

从错误信息看,编译器无法正确解析 Props 接口中的 Msg 自定义类型,导致生成 props 选项时出现类型转换错误。

解决方案:

  1. 使用运行时声明(推荐):
const props = defineProps({
  msg: {
    type: Object,
    required: true
  },
  msgId: {
    type: String,
    required: true
  }
})
  1. 如果需要类型提示,可以结合 JSDoc 注释:
/**
 * [@type](/user/type) {import('@/model/chat.uts').Msg}
 */
const props = defineProps({
  msg: {
    type: Object,
    required: true
  },
  msgId: {
    type: String,
    required: true
  }
})
回到顶部