uniapp x中defineProps能用自定义类型吗
uniapp x中defineProps能用自定义类型吗
<code class="language-javascript">
<script setup>
import { Msg } from '@/model/chat.uts'
interface Props {
msg : Msg,
msgId : String
}
const props = defineProps<Props>()
</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<id>, String, > , Object as PropType<avatar>, String, > , Object as PropType<atUserList>, Array<String>, > , Object as PropType<conversationID>, String, > , Object as PropType<conversationType>, String, > , Object as PropType<flow>, String, > , Object as PropType<from>, String, > , Object as PropType<nick>, String, > , Object as PropType<to>, String > , Object as PropType<type>, String > , Object as PropType<time>, Number > , Object as PropType<text>, MsgText > ], required: true },
</code>
1 回复
在 uni-app x 中,defineProps 目前不支持直接使用 TypeScript 接口或自定义类型作为泛型参数。虽然 H5 端可能能够运行,但在原生平台(如 Android)上会编译失败。
从错误信息看,编译器无法正确解析 Props 接口中的 Msg 自定义类型,导致生成 props 选项时出现类型转换错误。
解决方案:
- 使用运行时声明(推荐):
const props = defineProps({
msg: {
type: Object,
required: true
},
msgId: {
type: String,
required: true
}
})
- 如果需要类型提示,可以结合 JSDoc 注释:
/**
* [@type](/user/type) {import('@/model/chat.uts').Msg}
*/
const props = defineProps({
msg: {
type: Object,
required: true
},
msgId: {
type: String,
required: true
}
})

