gpt4 book ai didi

typescript - 什么是 Vue 3 组合 API 定义方法的类型安全方式

转载 作者:行者123 更新时间:2023-12-04 07:52:07 24 4
gpt4 key购买 nike

我正在使用 Vue 的组合 API(在 Vue.js 3 中)并主要在 setup() 中构建我的组件逻辑。而accessing my own props via setup(props) 很简单,我无法将此处定义为 methods 的函数公开以类型安全的方式。

以下工作,但我需要任意转换,因为没有暴露给 TypeScript 的方法接口(interface)。

<!-- MyComponent.vue -->

<script lang='ts'>
// ...
export default defineComponent({
setup() {
// ...
return {
publicFunction: async (): Promise<void> => { /* ... */ };
}
}
});

</script>
<!-- AppComponent.vue -->

<template>
<MyComponent ref="my"/>
</template>

<script lang='ts'>

export default defineComponent({
async setup() {
const my = ref();

async func() {
await (my.value as any).publicFunction(); // <-- gross!
}

return { my, func };
}
});

</script>

methods 中定义我的函数不是一种选择,因为那样的话,我将无法从设置中访问它。

最佳答案

您正在寻找 InstanceType .

import MyComponent from 'path/to/the/component';

export default defineComponent({
async setup() {
const my = ref<InstanceType<typeof MyComponent>>();

async func() {
await my.value?.publicFunction();
}

return { my, func };
}
});

这种方法的一个警告是(如您所见)您必须使用 optional chainingnon-null assertion operator ,除非您将初始/默认实例作为参数传递给 ref() 函数;否则,TypeScript 会将其标记为“可能未定义”。

在大多数情况下,如果您确定它总是会被定义,您可以使用 as-syntax 将它类型转换为一个空对象。 .

const my = ref({} as InstanceType<typeof MyComponent>);

async func() {
await my.value.publicFunction();
}

关于typescript - 什么是 Vue 3 组合 API 定义方法的类型安全方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66907606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com