假设我有这样的输入组件:
import { defineComponent } from "@vue/runtime-core"
export default defineComponent({
inheritAttrs: false,
setup(props, { attrs }) {
return () => (
<div>
<input type="text" {...attrs} />
</div>
)
}
})现在,我像这样使用这个组件并提供type="password"属性:
import { defineComponent } from "@vue/runtime-core"
import Input from "./components/input"
export default defineComponent({
setup(props, { attrs }) {
return () => <Input type="password"></Input>
}
})但是Typescript抱怨道:
Property 'type' does not exist on type 'IntrinsicAttribute'> & VNodeProps & AllowedComponentProps & ComponentCustomProps>'发布于 2021-03-20 19:22:22
因此,我不是Vue.JS专家(请告诉我它是否不起作用以及原因),但经过一些研究后,我发现必须通过将props对象添加到defineComponent来键入props。这将告诉TypeScript您可以传递特定的道具。
import { defineComponent } from "@vue/runtime-core"
export default defineComponent({
inheritAttrs: false,
props: {
type: String // this is the typing (warning: you cannot use typescript types here)
}
setup(props, { attrs }) {
return () => (
<div>
<input type={props.type ?? "text"} {...attrs} />
</div>
)
}
})您可能会问??操作符是做什么的。我喜欢称它为“默认运算符”,因为它将其前面的值默认为它之前的值,以及它后面的值。在本例中,这意味着如果props.type为undefined或null,它将用"text"替换它。
https://stackoverflow.com/questions/66684622
复制相似问题