Adding types to computed properties in Vue 3's Composition API is a seamless process

Having an issue where I am trying to add type to computed but keep encountering this error:

Overload 1 of 2, '(getter: ComputedGetter<AuthFormType>, debugOptions?: DebuggerOptions | undefined): ComputedRef<AuthFormType>', gave the following error
. Any ideas on how to properly add type to computed?

File: Auth.vue

type AuthFormType = 'Form1' | 'Form2';
const getForm = computed<AuthFormType>(
  () => tabs.value.find((tab) => tab.id === currentTab.value)!.component, // will return Form1 or Form2
);

Adding a simple type like string as shown in the documentation here works, but I specifically need to incorporate the type AuthFormType.

Answer №1

When it comes to computed properties, there's usually no need to explicitly specify the type since it can be inferred from the return value. https://i.stack.imgur.com/KO7py.png

As shown in my VS Code "peek type definition" hover feature, the correct type ComputedRef<AuthFormType> is automatically detected. However, if you still prefer to define the type explicitly for the computed property, you can import and utilize the same ComputedRef interface.

import { computed, ref, ComputedRef } from 'vue';
import type { Ref } from 'vue';

interface tabObj {
  id: number;
  component: AuthFormType;
}
const tabs: Ref<tabObj[]> = ref([]);
const currentTab = ref(0);

type AuthFormType = 'Form1' | 'Form2';
const getForm: ComputedRef<AuthFormType> = computed(
  (): AuthFormType =>
    tabs.value.find(tab => tab.id === currentTab.value)!.component
);

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

TypeScript's type casting will fail if one mandatory interface property is missing while an additional property is present

While running tsc locally on an example file named example.ts, I encountered some unexpected behavior. In particular, when I created the object onePropMissing and omitted the property c which is not optional according to the interface definition, I did not ...

I encounter an issue when trying to declare an enum in TypeScript

At line 26 in my typescript file, the code snippet below shows an enum definition: export enum ItemType { Case = 'Case', Study = 'Study', Project = 'Project', Item = 'Item', } I am currently using Visual Stu ...

What is the correct way to add type annotations to an Axios request?

I have meticulously added type annotations to all endpoints in my API using the openapi-typescript package. Now, I am looking to apply these annotations to my Axios requests as well. Here is a snippet of code from a Vue.js project I have been developing: ...

TypeScript does not verify keys within array objects

I am dealing with an issue where my TypeScript does not flag errors when I break an object in an array. The column object is being used for a Knex query. type Test = { id: string; startDate: string; percentDebitCard: number, } const column = { ...

Creating subclass mappings and defining subclasses dynamically using Typescript at runtime

I am puzzled by the structure of 3 classes: A, B, and C. Both B and C extend the abstract class A. abstract class A { public name: string; constructor(name: string) { this.name = name; } abstract getName(): string; } class B extends A { g ...

The React useState Props error message TS2322: Cannot assign type 'string' to type 'number'

I'm attempting to pass Props to React useState Hooks. Both of my props are required and should be numbers, but I keep receiving a Typescript error stating: Type 'string' is not assignable to type 'number'. TS2322 However, I am ...

Updating text inputs in Angular can be done more efficiently using Angular Update

I need to make adjustments to an Angular application so that it can run smoothly on older machines. Is there a more efficient method for updating a text input field without using (keyup) to update after each keystroke? I haven't been able to find any ...

Tips for effectively managing index positions within a dual ngFor loop in Angular

I'm working on a feedback form that includes multiple questions with the same set of multiple choice answers. Here's how I've set it up: options: string[] = ['Excellent', 'Fair', 'Good', 'Poor']; q ...

Challenges with overwriting TailwindCSS classes within a React component library package

I just released my very first React component on NPM. It's a unique slider with fractions that can be easily dragged. Check it out here: Fractional Range Slider NPM This slider was created using TailwindCSS. During bundling, all the necessary classe ...

MatDialog displaying no content

I found this tutorial on how to implement a simple dialog. The issue I'm facing is that the dialog appears empty with no errors in the console. Even after making changes to my dialog.component.html or dress-form.ts, nothing seems to reflect in the o ...

Submit information by utilizing' content-type': 'application/x-www-form-urlencoded' and 'key': 'key'

Attempting to send data to the server with a content-type of 'application/xwww-form-urlencode' is resulting in a failure due to the content type being changed to application/json. var headers= { 'content-type': 'applica ...

Divide the enhanced document into sections using TypeScript

In my project, I am working with Material UI and TypeScript. I have noticed that I need to declare the Theme interface and ThemeOptions in the same file for it to work properly. Is there a more efficient way to separate these declarations from the main t ...

A programming element that is capable of accessing a data member, but mandates the use of a setter method for modifications

I am unsure whether I need a class or an interface, but my goal is to create an object with a member variable that can be easily accessed like a regular variable. For example: interface LineRange { begin: number; end: number; } However, I want th ...

Changing the way in which text is selected and copied from a webpage with visible white space modifications

After working on developing an HTML parser and formatter, I have implemented a new feature that allows whitespace to be rendered visible by replacing spaces with middle dot (·) characters and adding arrows for tabs and newlines. You can find the current ...

Issues with Nuxt 3 middleware causing layout to fail updating post-navigation when using distinct login layout

Encountering a challenge in Nuxt 3 where the layout fails to update properly after navigation in a middleware, particularly when utilizing different layouts for the login page versus other pages. Here's an outline of the configuration: A middleware i ...

Generating automatic generic types in Typescript without needing to explicitly declare the type

In the scenario where I have an interface containing two functions - one that returns a value, and another that uses the type of that value in the same interface - generics were initially used. However, every time a new object was created, the type had to ...

What is the capability of dynamically generating an index in Typescript?

Can you explain why the Typescript compiler successfully compiles this code snippet? type O = { name: string city: string } function returnString(s: string) { return s } let o1: O = { name: "Marc", city: "Paris", [returnString("random")]: ...

Solving runtime JavaScript attribute issues by deciphering TypeScript compiler notifications

Here is a code snippet I am currently working with: <div class="authentication-validation-message-container"> <ng-container *ngIf="email.invalid && (email.dirty || email.touched)"> <div class="validation-error-message" *ngIf=" ...

The return type is not undefined but the switch covers all possibilities

I'm struggling to understand the issue with this simple example interface List { "A": false, "B": false, } // The function is missing a return statement and its return type does not include 'undefined'.ts(2366) / ...

Steps to display a modal dialog depending on the category of the label

I'm encountering an issue where clicking on different labels should show corresponding modal dialogs, but it always displays the same modal dialog for both labels ("All Recommendations"). Can anyone offer guidance on how to resolve this problem? Thank ...