A guide on exporting the data type of a computed property in Vue3

I'm facing a challenge with my Vue3 component that interacts with GraphQL requests. After receiving a large JSON response, I utilize a computed property to extract the necessary value. Now, I aim to pass this extracted value as a prop to a child component.

The issue arises in the child component where I need to specify the type for my defineProps call. To accommodate the computed value, it's crucial to have the correct type definition within the child component. The computed property itself is extensive, making manual typing outside of the component undesirable. Instead, I opt to leverage the typeof operator.

My question is, how can I export this type effectively?

// Parent.vue
<script setup lang="ts">
const { results } = useQuery(...)
const myComputed = computed(() => results.nested.item.is.here)
</script>

<template>
  <Child :passToMe="myComputed" />
</template>


// Child.vue
const props = defineProps<
  passToMe: ???
>()

I've come across the option of exporting from a separate <script> tag within the component. However, this method doesn't provide access to the computed property defined in my <script setup>.

While considering utilizing the type of the GraphQL results, the nested structure poses a complication in implementation.

Transferring the query operation to the Child component solely for type extraction isn't feasible, as other components also rely on the <Child> component and the specific type enforced by the computed property in the <Parent>. This minimum type requirement is essential in maintaining consistency.

Given these constraints, how can I efficiently export this type for multiple implementations?

Answer №1

If you want to retrieve the type of "results.nested.item.is.here", you can utilize the typeof operator.

const results = {
  nested: { 
    item: {
      is: {
        here: "hello"
      }
    }
  }
}
export type propsType = typeof results.nested.item.is // { here: string }

Next, import the type propsType into your Child component.

It's important to note that typeof works differently in JavaScript runtime and TypeScript type declarations. It provides the JavaScript type such as "string", "object", or "number".

export const runTimeType = typeof results.nested.item.is // "object"

An alternative approach is defining an interface for the results:

interface IResult {
  nested : {
    item : {
      is : {
        here: string
      }
    }
  }
}

const results: IResult = {
  nested: { 
    item: {
      is: {
        here: "hello"
      }
    }
  }
}

export type propsType = IResult["nested"]["item"]["is"] // { here: string }

Exercise caution when using typeof as changes in the result type returned by useQuery(...) could unintentionally affect the props type of Child leading to potential bugs if the new type is incompatible with how Child handles the data.

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

How can I switch the header bar button from "login" to "logout" in a React

I am currently working on a React and Next.js frontend template, specifically focusing on creating a dashboard with a header bar and login button. Once a user logs in, the login button should change to a logout button and the links in the header should als ...

How to convert typescript path aliases into relative paths for NPM deployment?

I am currently working on a typescript project that utilizes paths for imports. For instance: "paths": { "@example/*": ["./src/*"], } This allows the project to import files directly using statements like: import { foo } from "@example/boo/foo"; Whe ...

How do I implement a dynamic input field in Angular 9 to retrieve data from a list or array?

I'm looking to extract all the strings from the Assignes array, which is a property of the Atm object, and populate dynamic input fields with each string. Users should be able to update or delete these strings individually. What approach can I take us ...

Vuex State: Array is devoid of any elements

I've encountered an issue with the "genreRankings" state-variable in my "store.js" that refuses to update. Can anyone shed light on why this might be happening? When interacting with the Store from my Component, I'm using the following methods: ...

Alter the entity type when passing it as a parameter

Trying to alter the Entity type, I am invoking a function that requires two parameters - one being the entity and the other a location. However, when trying to assign a Type for the first entity, it throws an error: Error: Argument of type 'Node<En ...

Steps for confirming a property setting on an interface

I am working with the following interface export interface Command { id: CommandId; disabled: boolean; } My goal is to verify that the 'disabled' property has been changed. Here are my attempts: 1) Creating an object and checking if t ...

Using ternary operator to set multiple variables in setState

Conditional Operator for Setting State in React I am wondering if there is a way to set the state with a variable that holds the correct state value using setState method. interface state { isfiltered: array<boolean> } this.setState({ ...

Attempting to access the $ref property in Vue results in an undefined value

When I try to work with $refs in Vue, I keep getting undefined. <div ref="table-ref">This is a sample reference element</div> In my Vue method, I attempt to access the ref and apply a scroll to it const tableRef = this.$refs['ta ...

Encountering issues while attempting to transmit several files to backend in React/NestJS resulting in a BAD REQUEST error

My goal is to allow users to upload both their CV and image at the same time as a feature. However, every time I attempt to send both files simultaneously to the backend, I encounter a Bad Request error 400. I have made various attempts to troubleshoot th ...

Is there a way to verify if a mixin has been successfully applied to the component?

I am currently conducting tests on a VueJS 2 application using the vue-test-utils library. I am striving to verify whether the specific component has received the mixin. This involves mounting the component utilizing the mount function and then attempting ...

What causes the difference in behavior between using setInterval() with a named function as an argument versus using an anonymous function?

I can't seem to figure out why using the function name in setInterval is causing issues, while passing an anonymous function works perfectly fine. In the example that's not working (it's logging NaN to the console and before the first call, ...

The error "Cannot access property afs (Angularfirestore) of undefined in the collection.set()" occurred

In the current code snippet below, I am iterating over a collection of data and updating a field if the email matches. The issue arises when trying to set new values where it crashes. The iteration process itself functions correctly, with afs being Angular ...

send the checkbox control's model value back to the parent control in Vue3

I've implemented a wrapper control for checkboxes that closely resembles my textbox control. This approach ensures consistent validation and design throughout the application. While I was successful in getting it to work for textboxes, I encountered s ...

Showing an error message upon submission in Angular 4 according to the server's response

Struggling for hours to display an error message when a form submits and returns an error status code. The solution seems elusive... In the login form component below, I've indicated where I would like to indicate whether the form is valid or invalid ...

When utilizing TS Union Types from an Array, the resulting type will consistently be a

After reading this response, I decided to create some union types from a string[] in order to return a list of valid type values. However, instead of that, the type ends up accepting any string value. const arrayDays = Array.from(Array(32).keys(), (num) =& ...

Retrieve the service variable in the routing file

How do I access the service variable in my routing file? I created a UserService with a variable named user and I need to use that variable in my routing file. Here is the approach I tried, but it didn't work: In the routing file, I attempted: cons ...

The current context for type 'this' cannot be assigned to the method's 'this' of type '...'

Currently, I am in the process of defining type definitions (.d.ts) for a JavaScript library. In this specific library, one of the methods accepts an object of functions as input, internally utilizes Function.prototype.bind on each function, and then expos ...

Store a video file on your device's memory

Currently, I am storing simple strings in local storage. However, I am now facing the issue of wanting to save videos and images to local storage. Due to the limitations of localStorage supporting only strings, I am unsure of how to achieve this. If you h ...

What is the best way to enable a child category on a treeview within a Vue component?

I am working with two vue components. The first component (parent component) looks like this: <template> ... <ul class="filter-category" v-for="list in categories"> <list-category :data="list" :category-id="category ...

Is the "Angular is not functioning" error message the result of a missing import?

Encountering an 'is not a function' error in Angular 7 / TypeScript 3, using an EventEmitter. This issue has been extensively discussed (a b), but solutions have not garnered many upvotes (a b c d e f). I am close to resolving it, but need s ...