英文:
defineEmit in composition API and typecast it properly in my composable
问题
I define an emit in my <script setup lang="ts">
and I want to send that emit to my composable to actually do the emitting for me.
However, I do need to cast my received parameter to something (because any
is obviously not very nice and unknown doesn't think emit
is a function)
I have the below code:
export type EmitType = {
'search': [value: string]
}
And I initialize the composable with something like this:
<script setup lang="ts">
const emit = defineEmits<EmitType>();
useComposable(emit);
</script>
I then use EmitType
to cast my emit
parameter
const useMyComposable(emit: EmitType) {
emit('search', 'a string');
}
By doing the above my emit()
in the composable gives the error:
This expression is not callable.
Type 'EmitType' has no call signatures.
Which I understand because defineEmits
most likely has a different type.
So in short my question is:
How can I properly define emit
in my composable to be error-free, not use any
as a type and have the proper intellisense?
英文:
I define an emit in my <script setup lang="ts">
and I want to send that emit to my composable to actually do the emitting for me.
However, I do need to cast my received parameter to something (because any
is obviously not very nice and unknown doesn't think emit
is a function)
I have the below code:
export type EmitType = {
'search': [value: string]
}
And I initialize the composable with something like this:
<script setup lang="ts">
const emit = defineEmits<EmitType>();
useComposable(emit);
</script>
I then use EmitType
to cast my emit
parameter
const useMyComposable(emit: EmitType) {
emit('search', 'a string');
}
By doing the above my emit()
in the composable gives the error:
This expression is not callable.
Type 'EmitType' has no call signatures.
Which I understand because defineEmits
most likely has a different type.
So in short my question is:
How can I properly define emit
in my composable to be error-free, not use any
as a type and have the proper intellisense?
答案1
得分: 1
I think this should do the trick. As your typescript error said, your previous type was not callable. This is.
type EmitType = {
(event: "search", value: string): void;
};
const emit = defineEmits<EmitType>();
const runEmit = (emit: EmitType) => {
emit("search", "string");
};
edit:
See https://vuejs.org/guide/typescript/composition-api.html#typing-component-emits
英文:
I think this should do the trick. As your typescript error said, your previous type was not callable. This is.
type EmitType = {
(event: "search", value: string): void;
};
const emit = defineEmits<EmitType>();
const runEmit = (emit: EmitType) => {
emit("search", "string");
};
edit:
See https://vuejs.org/guide/typescript/composition-api.html#typing-component-emits
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论