正确的 vue3 setup() 参数的 typeScript 类型

B45*_*45i 4 typescript vue.js

我正在使用带有打字稿的 vue3,并且我正在使用组合 API。

export default {
    setup(props, context) {
    },
};
Run Code Online (Sandbox Code Playgroud)

这会引发如下错误

编译失败。

src/components/LoginForm.vue:20:11
TS7006: Parameter 'props' implicitly has an 'any' type.
    18 |
    19 | export default {
  > 20 |     setup(props, context) {
       |           ^^^^^
Run Code Online (Sandbox Code Playgroud)

我知道这可以通过制作props,context类型 any 来解决,但这会破坏 TypeScript 的目的。

VS Code 智能感知向我展示了以下类型,但我无法从这些类型中找到模块被导出。

setup?: ((this: void, props: {}, ctx: SetupContext<EmitsOptions>) => void | RenderFunction
Run Code Online (Sandbox Code Playgroud)

setup函数的正确类型是什么,从哪里导出?。

Kan*_*now 7

无法推断道具,因为您忘记使用defineComponent方法来创建组件。要解决此问题并让Vue使道具成为红外线,您需要将要导出的整个对象包装在defineComponent方法中。

更多关于 defineComponent

<script lang="ts">示例的Vue 3组合物API组分的一部分应该看起来:

export default defineComponent({
  name: "PersonComponent",
  props: {
    firstName: {
      type: String,
      required: true
    },
    lastName: {
      type: String,
      required: true
    },
    age: {
      type: Number,
      required: true
    }
  },
    setup(props) {
    const firstName = props.firstName;
    const lastName = props.lastName;
    const age = props.age;
    return {
      firstName,
      lastName,
      age
    };
  }
})
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


在此处输入图片说明

对于更复杂的类型,例如接口,您需要使用Object as PropType<T>( Object as PropType<IconProps>)。更多关于PropType<T>