簡體   English   中英

為 vue3 setup() arguments 正確的 typeScript 類型

[英]Correct typeScript Type for vue3 setup() arguments

我正在使用帶有 typescript 的 vue3,並且我正在使用組合 API。

export default {
    setup(props, context) {
    },
};

這會引發如下錯誤

編譯失敗。

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

我知道這可以通過制作任何類型的propscontext來解決,但這會破壞 TypeScript 的目的。

VS Code intellisense 向我展示了以下類型,但我無法從這些類型中找到導出的模塊。

setup?: ((this: void, props: {}, ctx: SetupContext<EmitsOptions>) => void | RenderFunction

setup function 的正確類型是什么,以及從哪里導出?

無法推斷道具,因為您忘記使用defineComponent方法來創建組件。 要解決此問題並讓Vue的道具成為紅外線,您需要包裝您在defineComponent方法中導出的整個 object。

更多關於defineComponent

示例 Vue 3 組合 API 組件的<script lang="ts">部分應如下所示:

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
    };
  }
})

在此處輸入圖像描述


在此處輸入圖像描述

對於更復雜的類型,例如接口,您需要使用Object as PropType<T>Object as PropType<IconProps> )。 更多關於PropType<T>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM