我在Vue3项目中有一个组件,它可以是一个字符串,也可以是一个对象。
所以就像这样:
import { defineComponent } from 'vue'
const Component = defineComponent({
props: {
book: {
type: [String, Object]
}
}
})但是,如果它是一个对象,我想添加一个类似于so的类型(取自vue3文档):
import { defineComponent, PropType } from 'vue'
interface Book {
title: string
year?: number
}
const Component = defineComponent({
props: {
book: {
type: Object as PropType<Book>
}
}
})我的问题是,我如何将两者结合起来(这是行不通的,因此我的问题):
import { defineComponent, PropType } from 'vue'
interface Book {
title: string
year?: number
}
const Component = defineComponent({
props: {
book: {
type: [String, Object as PropType<Book>]
}
}
})发布于 2021-05-05 22:57:13
对该支柱类型使用函数表达式:
const Component = defineComponent({
props: {
book: {
type: [String, () => Object as PropType<Book>]
}
},
mounted() {
const isBook = (obj: any): obj is Book => 'title' in obj // eslint-disable-line @typescript-eslint/no-explicit-any
if (isBook(this.book)) {
console.log(this.book.title)
}
}
})https://stackoverflow.com/questions/67400712
复制相似问题