Eliminate private TypeScript class properties from an object by using Vue 3's ref and reactive features

When an object with private properties or methods is passed to ref() or reactive(), the resulting proxy no longer contains the private properties.

Consider the following class:

class Pirate {
     name: string;
     age: number;
     private dream : string;

     constructor(name: string, age: number, dream: string) {
       this.name = name;
       this.age = age;
       this.dream = dream;
     }
   }
   

Creating a ref of type Pirate will lead to a Typescript error stating :

Property 'dream' is missing...

You can view an example here.

I would like to create a reactive object while maintaining the confidentiality of private properties. Is it possible in Vue 3?

The same issue occurs with reactive() as well.

Answer №1

I'm encountering a similar issue as well. After reading @alex87's comment and exploring the discussion on Mapped types: remove private interface, I have come up with a potential solution:

Pick<Pirate, keyof Pirate>

If you find yourself needing this solution frequently, you could create a helper type using the approach outlined in the aforementioned Stack Overflow answer:

type PublicInterface<T> = Pick<T, keyof T>;

(A big thanks to the original contributors for sharing their insights.)

Answer №2

There is no need to import Ref, as const captain = ref(...) will automatically be assigned as type Ref.
If you designate dream as private, it can only be accessed within the Pirate class.
To access dream outside of the class, you can create a method like this: getDream() { return this.dream }.
Vue SFC Playground

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 utilizing the "??=" syntax in Typescript

let x; x ??= 'abc' console.log(x); // abc Running the code above in the browser console does not cause any issues. However, when attempting to run it in TypeScript, an error is thrown. SyntaxError: Unexpected token '??=' Here is my c ...

What is the syntax for declaring a variable as a string or a function with parameters?

Is it possible to define a variable in TypeScript like a string or as a Function, but with specific parameters? I am aware of how to define a string actionGetData: string; and a function actionLoaded?(event: any, ui: any): void;, but when I try to define ...

Discovering an object by its id in vue-router parameters and subsequently sending its attributes to a template within Vue

In my ContactDetails component, I am fetching data from the vuex state and storing it in a contacts array. Then, within a computed property, I am attempting to find and return an object based on the id prop passed from the router params. Here is the code ...

Angular: How to Disable Checkbox

Within my table, there is a column that consists solely of checkboxes as values. Using a for loop, I have populated all values into the table. What I have accomplished so far is that when a checkbox is enabled, a message saying "hey" appears. However, if m ...

Implementing automatic token refreshing and automatic logout features in Vue

I am a novice web developer looking to enhance my skills. For my initial project, I decided to incorporate Laravel and Vue. My main objectives are to: Implement an auto-logout feature after 3 minutes of user inactivity Create an automatic ping to my token ...

The functionality of Highcharts-more.js is not functioning properly within a project set up using vue-cli

Recently, I have been working on a vue-cli project and attempting to create a polar chart similar to the one shown here: https://www.highcharts.com/demo/polar-spider To achieve this, I needed to install and import the highcharts and highchart-more librari ...

Even when Chrome is disconnected from the internet, the Ajax HTTP request remains in a pending state

Starting a new VueJS-Project and integrating a workbox-backgroundSync in my progressive web application. Testing this workbox plugin requires disconnecting my device (chrome) from the internet and initiating a POST-request. Even with no internet connection ...

Unleashing the Power of Vuejs: Setting Values for Select Options

I have a specific requirement in my Vue application where I need to extract values from an XLS file and assign them to options within a select dropdown. Here is what I currently have: <tr v-for="header in fileHeaders" :key="header"&g ...

The PayPal checkout component in Vue remains in sandbox mode

I've been facing challenges when trying to transition to the live environment. It's perplexing how everything seems to function seamlessly in sandbox mode, yet there appears to be no clear guidance on switching to production or it simply doesn&ap ...

Trigger a Vue.js action once an element is generated using v-if

One of the challenges I am facing is loading an element based on a condition (v-if). <div id="food-content" v-if="activeFood" v-cloak> To load it, I use this line of code: app7.activeFood = food; After the element is instantiated, I aim to apply ...

Passing a variable from one child component to another triggers an ExpressionChangedAfterItHasBeenCheckedError in Angular

My situation involves passing information to two children components. parent.component.html <childA [loading]="loading"> <childB (loadingChanged)="loadingChangedHandler($event)"></childB> </childA> parent.component.ts loadin ...

How can I add an object to an array of objects in Vue.js?

Hey there! I'm new to Vue and currently working on understanding the whole concept of Vue and how to use it. Right now, my focus is on learning lists. JS: Vue.config.productionTip = false; new Vue({ el: '#app', data: { items: [ ...

Having trouble removing objects from a map results in having to invoke the function three times

I am facing an issue with the function findPrice where I need to call it multiple times to delete objects that match a specific price. The problem arises when dealing with large maps and two functions. Here is the JSON format: [ { _id: 5c6c408dbec3ab457c ...

Innovative solution for detecting and replacing undefined object properties in Angular 2 with TypeScript

After encountering the issue of core.umd.js:3523 ORIGINAL EXCEPTION: Cannot read property 'fullName' of undefined I realized that the Exception stemmed from a Template trying to access a specific property: {{project.collaborators["0"]["fullN ...

What causes images to unexpectedly expand to fill the entire screen upon switching routes in Next.js?

I'm in the process of creating a website using Next and Typescript, with some interesting packages incorporated: Framer-motion for smooth page transitions Gsap for easy animations One issue I encountered was when setting images like this: <Link&g ...

How to properly convert JSON into a string within a nested object

Below is the JSON that I am passing and its result when logged in the console: boundary: Array(1) 0: points: Array(98) 0: {x: 117.5, y: 99} 1: Point {x: 116.5, y: 100} 2: Point {x: 116.5, y: 103} 3: Point {x: 114.5, y: 109} 4: Point {x: 113.5, y: 116} 5: P ...

Using static props to transmit API call information

I am developing a Vue.js application that requires multiple API calls. I am utilizing the tmdb API to incorporate sections for popular, upcoming, and top-rated movies in my app. All of these sections use the same API call, which is shown below (for popular ...

How can I show a limited number of columns in a mat-table in Angular 6 depending on a specific condition?

Currently, I am facing an issue with my mat table as it contains several columns. In a specific scenario, I need to hide two of these columns. Typically, for a regular table, we would use a simple ngIf condition to achieve this. However, in the case of thi ...

Is It Possible to Save Data to Local Storage Using Vue.js?

I am currently working on storing data using Vue.js and local storage. By writing localStorage.set('something', 5) in my main.js file, I can view the data in the Chrome dev tools under the 'Storage' section in the 'Application&apo ...

What is the correct way to understand nested and intricate types in Typescript?

There seems to be an issue with Typescript not properly inferring complex and nested types at times. I'm trying to figure out if this is a bug or if there's a mistake on my end. And if it's a mistake on my end, what is the most effective wa ...