Vue TSX - 如何告诉 Typescript 在可重用组件中允许使用 HTML 属性?

San*_*jay 5 jsx typescript vue.js tsx

假设我有这个输入组件:

import { defineComponent } from "@vue/runtime-core"

export default defineComponent({
    inheritAttrs: false,
    setup(props, { attrs }) {
        return () => (
            <div>
                <input type="text" {...attrs} />
            </div>
        )
    }
})
Run Code Online (Sandbox Code Playgroud)

现在,我像这样使用这个组件并提供type="password"属性:

import { defineComponent } from "@vue/runtime-core"
import Input from "./components/input"

export default defineComponent({
    setup(props, { attrs }) {
        return () => <Input type="password"></Input>
    }
})
Run Code Online (Sandbox Code Playgroud)

但是打字稿抱怨:

Property 'type' does not exist on type 'IntrinsicAttribute'> & VNodeProps & AllowedComponentProps & ComponentCustomProps>'
Run Code Online (Sandbox Code Playgroud)

bla*_*e20 5

所以我不是 Vue.JS 专家(请告诉我它是否不起作用以及为什么),但经过一些研究我发现你必须props通过向.js添加一个props对象来输入defineComponent. 这将告诉 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>
        )
    }
})
Run Code Online (Sandbox Code Playgroud)

您可能会问??接线员是做什么的。我喜欢称它为“默认操作符”,因为它默认了它之前的值和它之后的值。在这种情况下,这意味着 if props.typeisundefinednull它将替换为"text".