TypeScript / Vue 3:注入变异函数导致 TypeScript 错误“对象类型为‘未知’”

chudy91

我是 TypeScript 的新手,并尝试将它与 Vue 3 组合 API 一起使用并提供/注入。假设在父组件中A我有这样的事情:

// Parent component A

import { provide, ref } from 'vue';
import ScoreType from "@/types/Score";

setup() {
  ..
  const score = ref<ScoreType[]>([]);
  const updateScore = (val: ScoreType) => {
    score.value.push(val);
  };

  provide('update_score', updateScore);  
  ..
}

...然后想要updateScore在子组件中注入函数,B以便能够更新父组件中的值A这是文档推荐的)。不幸的是,我收到了 TS 错误Object is of type 'unknown'

// Child component B

import { inject } from 'vue';

setup() {
  ..
  const updateScore = inject('update_score');
  const checkAnswer = (val: string) => {
    updateScore({ /* ScoreType object */ });  // → Object is of type 'unknown'.
  }
  ..
}

我应该怎么做才能修复 TypeScript 错误?我找不到关于在 TS 中注入更新函数的任何示例。

猎豹

让我们首先为我们的updateScore()函数声明一个类型

// @/types/score.ts
export type ScoreType = { points: number };

export type UpdateScoreFunction = (val: ScoreType) => void;

现在我们需要声明一个InjectionKey将保存我们提供/注入的变量(在本例中为函数)的类型信息。Vue 文档中的更多信息

让我们创建一个单独的文件夹来存储我们的密钥并保持井井有条:

// @/symbols/score.ts
import { InjectionKey } from "vue";
import { UpdateScoreFunction } from "@/types/score";

export const updateScoreKey: InjectionKey<UpdateScoreFunction> = Symbol("updateScore");

在我们的父组件中(A)

<script lang="ts">
import { defineComponent, provide, ref } from "vue";

import { ScoreType, UpdateScoreFunction } from "@/types/score";
import { updateScoreKey } from "@/symbols/score";

export default defineComponent({
  setup() {
    const score = ref<ScoreType[]>([]);
    
    // Actually, adding ': UpdateScoreFunction' is optional 
    const updateScore: UpdateScoreFunction = function (val: ScoreType) {
      score.value.push(val);
    };

    // Replace the string with InjectionKey
    provide(updateScoreKey, updateScore);

    // ...
  },
});
</script>

在我们的子组件中(B)

<script lang="ts">
import { defineComponent, inject } from "vue";
import { updateScoreKey } from "@/symbols/score";

export default defineComponent({
  setup() {

    // Replace the string with InjectionKey
    const updateScore = inject(updateScoreKey);

    // In case the `updateScoreKey` is not provided by the parent component..
    if (updateScore === undefined) {
      throw new Error('Failed to inject "updateScore"');
    }

    const checkAnswer = (val: string) => {

      // ...

      // The error is gone
      updateScore({ 
        points: Math.floor(Math.random() * 100),
      });
    };

    // ...
  },
});
</script>

这里提供的工作示例codesandbox.io/s/so-provide-inject

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章