I create an `emitHandler` in the composition API and ensure it is properly typecasted within my com

I have created an emit within my

<script setup lang="ts">
and I want to pass that emit to my composable so it can handle the emitting process.

However, I need to ensure that the received parameter is properly casted (as using any is not ideal, and it results in emit not being recognized as a function).

The code snippet below showcases this:

export type EmitType = {
    'search': [value: string]
}

To initialize the composable, I would do something like this:

<script setup lang="ts">
const emit = defineEmits<EmitType>();

useComposable(emit);
</script>

Then, I use EmitType to cast my emit parameter:

const useMyComposable(emit: EmitType) {
  emit('search', 'a string');
}

Despite this, when I call emit() within the composable, I encounter the following error:

This expression is not callable.
  Type 'EmitType' has no call signatures.

This issue arises due to potential differences in the type assigned by defineEmits.

In summary, my question is: What is the correct way to define emit within my composable to eliminate errors, avoid using any as a type, and enable proper intellisense?

Answer №1

My solution is to address the issue you are facing with typescript errors. The error indicates that your previous type was not callable, but I have provided a fix for this.

type EmitType = {
    (event: "search", value: string): void;
};

const emit = defineEmits<EmitType>();

const runEmit = (emit: EmitType) => {
    emit("search", "string");
};

Additionally, please refer to https://vuejs.org/guide/typescript/composition-api.html#typing-component-emits for further information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for minimizing the space between yAxes in Chart.js?

My data and configuration are as follows: { chartData: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple'], datasets: [ { label: '', backgroundColor: 'rgba( ...

How to pass parameters while updating parent values in VueJS using emit?

Explaining my dilemma with uploading images: In my form, users can upload images using the following code snippet: <input id="visualisation_upload" @change="onThumbnailChanged" name="visualisation_upload" accept="imag ...

Building a Mobile App with Ionic 2, Cordova, and Typescript: Leveraging the Power

I'm currently developing an Ionic 2 application using Typescript. To set preferences, I want to utilize the cordova plugin https://github.com/chrisekelley/AppPreferences/. There are a couple of challenges I am facing. Despite thorough research onlin ...

What could be causing the issue with these overload calls?

Hey there, I've encountered an issue while using createStore. Can someone please guide me on what I might be doing incorrectly? TypeScript error in /workspace/weatherAppTypescript/App/appfrontend/src/redux/store/index.ts(7,31): No overload matches th ...

Add a line break within a string retrieved from Firebase

Can anyone suggest a way to insert a new line in a string retrieved from a Firebase database? I attempted using the tag and "\n" without success. ...

Casting Types in TypeScript

Here is the TypeScript code I am using to create an ApolloClient: return new ApolloClient({ dataIdFromObject: (o) => o.uuid }); Upon compilation, I encountered the following error message: TS2339:Property 'uuid' does not exist on type ...

VS-Code is not a fan of accessors when targeting ES6

I can't seem to figure out this strange issue I'm having with VS-Code (1.13.1, MacOS). Every time I try to use a class getter or setter, I get the following error: [ts] Accessors are only available when targeting ECMAScript 5 and higher. The ...

How to properly pass a parameter value to an Angular service when using inject.get in the constructor

After experimenting with injecting services in Angular, I encountered an issue when trying to call LogService within GlobalErrorHandler. Despite my best efforts, the code below just wouldn't work. I discovered that the problem stemmed from not passin ...

Issue with Angular: ngForm object does not capture selected option

Revise to clean up unnecessary code. Having trouble displaying the selected option when I print the form object to the console. It's showing as undefined. Any guidance on what might be wrong with this code would be appreciated. Let me know if more in ...

The expected function is being executed, yet none of the inner functions are invoked

Currently, I am working on unit tests for an Angular application using Jasmine and Karma. One particular unit test involves opening a modal, changing values in a form, and saving them. Everything goes smoothly until it reaches the promise inside the open() ...

A reference to 'this' is not permissible within a static function in Types

Based on this GitHub issue, it is stated that referencing this in a static context is allowed. However, when using a class structure like the following: class ZController { static async b(req: RequestType, res: Response) { await this.a(req) ...

Dynamically attach rows to a table in Angular by triggering a TypeScript method with a button click

I need help creating a button that will add rows to a table dynamically when pressed. However, I am encountering an error when trying to call the function in TypeScript (save_row()). How can I successfully call the function in TypeScript and dynamically a ...

How can we optimize component loading in react-virtualized using asynchronous methods?

In my component, I have implemented a react-virtualized masonry grid like this: const MasonrySubmissionRender = (media: InputProps) => { function cellRenderer({ index, key, parent, style }: MasonryCellProps) { //const size = (media.submiss ...

How can one define a getter within an interface?

One of my classes is structured like this (only showing a portion here): export class LinkedListNode<t> extends windward.WrObject implements ILinkedListNode<t> { public get next(): LinkedListNode<t> { return this._next === thi ...

Error with Chakra UI and React Hook Form mismatched data types

Struggling with creating a form using ChakraUI and React-Hook-Form in TypeScript. The errors seem to be related to TypeScript issues. I simply copied and pasted this code from the template provided on Chakra's website. Here is the snippet: import { ...

Exploring the Node environment setup within Nest.js

Currently, I am in the midst of setting up a Nest.js project and seeking an efficient solution for defining the Node environment used by the ConfigService to load environment variables: import { Module } from '@nestjs/common'; import { ConfigSer ...

Types of Axios responses vary depending on their status codes

I am looking to create a specific type for axios responses based on the status code: types: type SuccessfulResponseData = { users: .... }; interface SuccessfulResponse extends AxiosResponse<SuccessfulResponseData, any> { status: 200; } ty ...

Unable to locate module in node_modules directory when attempting to import an image into TS

In my .tsx file, I am encountering an issue with the following code snippet: import L from 'leaflet'; import icon from 'leaflet/dist/images/marker-icon.png'; import iconShadow from 'leaflet/dist/images/marker-shadow.png'; The ...

How to detect changes in Angular2 forms

Exploring Angular2 4.0, I've created a FormGroup structured as follows: this.form = this._fb.group({ a: ['', [Validators.required]], b: ['', [Validators.required]], c: ['', [Validators.required]], ...

Utilizing files that do not have the extension '.ts' or '.tsx' within the 'ts_library' as dependencies

My current challenge involves importing a JSON file from TypeScript while utilizing the resolveJsonModule flag in my tsconfig. The problem lies in how I can provide this JSON file to ts_library since it seems unable to locate the file. This issue extends t ...