Is there a way to input argument values in Typescript?

Learning TypeScript has been quite a challenge for me, especially when it comes to typing. I recently tackled a problem while working on a Vue project with TypeScript:

Parameter 'data' implicitly has an 'any' type.

Here is the code snippet:

type usersTypes = {
  phone: number,
  age: number
}

const usersTest = computed(() => {
  const users: usersTypes = {
    phone: 99999999,
    age: 20
  }

  return users
})
const filtered = 'test'

function getUsers(data){  //Parameter 'data' implicitly has an 'any' type.
  console.log('data: ', data)
  console.log('users phone: ', data.users.phone) // Unsafe member access .users on an `any` value.
  console.log('filter: ', data.filter) // Unsafe member access .filter on an `any` value.
  
}

onMounted(() => {
  getUsers({
    users: usersTest.value,
    filter: filtered
  })
})   

Answer №1

Sharing this as an answer because explaining code snippets in comments can be challenging. Here is one way to tackle it:

class Person {
   phoneNumber: number;
   personAge: number;

   constructor(phoneNumber: number, personAge: number) {
      this.phoneNumber = phoneNumber;
      this.personAge = personAge;
   }
}

class PersonData {
   personInfo: Person; // keep in mind that classes define types
   criteria: string; // make sure to use the correct data type for your criteria

   constructor(person: Person, criteria: string) {
      this.personInfo = person;
      this.criteria = criteria;
   }
}

let examplePerson = new Person(123456, 20);
let information = new PersonData(examplePerson, "personAge");

function testPersonData(testData: PersonData) {
   console.log("Data:", testData);
   console.log("Phone Number:", testData.personInfo.phoneNumber);
   console.log("Criteria:", testData.criteria);
}

testPersonData(information);

Remember, there are multiple ways to approach this. The key is to be mindful of your data types and explicitly declare them.

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

Leverage Angular's filtering capabilities with a variety of input options

I am in need of help with a filter for my simple list of people, where each person has a name and a first name. I want to be able to search for a specific field or both fields at the same time. https://i.sstatic.net/pPRjO.png The HTML code is as follows: ...

Enhancing Angular Models with Property Decorators

In my Angular 8 application, I faced an issue where the backend model and frontend model are not identical. For example, the backend model stores dates in SQL format while I needed them in a JavaScript friendly format on the frontend. To tackle this probl ...

Integrating React frontend with Node JS backend on Kubernetes platform

Seeking guidance on the best approach for making API requests from a React Frontend Application to a Node JS backend application in a Kubernetes environment. Both are hosted within the same container, following this dockerfile structure: COPY frontend/pack ...

Issue with VueJs: When deleting child components that are created dynamically, the last one is always the

In my project, I have a parent component called customer which contains a child component named contact. Customers can add multiple contacts to the contact list. However, when attempting to remove a specific contact from the list, it always ends up remov ...

Saving a local JSON file in Angular 5 using Typescript

I am currently working on developing a local app for personal use, and I want to store all data locally in JSON format. I have created a Posts Interface and an array with the following data structure: this.p = [{ posts:{ id: 'hey man&ap ...

Vue JS - preventing button from being enabled until all validation errors have been resolved

I am facing an issue with my button that is supposed to be disabled until all validation requirements are met. Currently, the button only gets disabled after I click it for the first time and encounter validation errors. I need the button to be disabled ri ...

Managing the backspace function when using libphonenumber's AsYouTypeFormatter

I've been attempting to integrate the google-libphonenumber's AsYouTypeFormatter into a basic input field on a web form. For each key pressed by the user, I feed it into the inputDigit method. However, I've encountered an issue where when th ...

Collection of personalized forms where the parent is a FormGroup

One scenario I'm working on involves creating multiple custom formgroup classes that have FormGroup as their parent class, structured like this: export class CustomFormGroup1 extends FormGroup { //custom properties for this FormGroup const ...

Angular 2 forms are displaying ngvalid when input fields are marked as nginvalid

The form displays ngvalid because I have included the code like this: <form novalidate class="pop-form" (submit)="signUp()" #regForm="ngForm"> <div class="group"> <input type="text" [(ngModel)]="signUpData.name" [ngMode ...

Is there a way to implement jquery (or other external libraries) within Typescript?

Currently, I am diving into Typescript to enhance my skills and knowledge. For a project that is being served with Flask and edited in VSCode, I am looking to convert the existing JavaScript code to Typescript. The main reason for this switch is to leverag ...

What sets my project apart from the rest that makes TypeScript definition files unnecessary?

Utilizing .js libraries in my .ts project works seamlessly, with no issues arising. I have not utilized any *.d.ts files in my project at all. Could someone please explain how this functionality is achievable? ...

Utilizing Jest and nest.js for testing with absolute paths

Looking at my jest configuration inside the package.json: "jest": { "moduleFileExtensions": [ "js", "json", "ts" ], "moduleDirectories":["node_modules", "src" ...

The parameter 'NextApiRequest' cannot be assigned to the parameter 'Request'

I encountered a typescript issue that states: Argument of type 'NextApiRequest' is not assignable to parameter of type 'Request'. Type 'NextApiRequest' is not assignable to type '{ url: string; }'. Types of pro ...

exploration of unique npm packages with vue-loader in development

After configuring my project with vue-loader, I included several postcss plugins in the designated config file. Now, I aim to integrate the GSAP package (downloaded from npm). Where should I insert the code for webpack to recognize it? ...

Trouble with passing query parameters in generateStaticParams | Nextjs version 14.2.17

There is a list of projects on the parent page, displayed using client-side rendering with useEffect. When a user clicks on a specific project, the following code snippet is executed: <Link key={index} prefetch={true} href={{ pathnam ...

Struggling to successfully integrate the Clarity library into my Angular project using the command "ng add @clr/angular," encountering the error message "ERESOLVE unable to resolve dependency tree."

Currently, I am working on a project in Angular that requires the installation of the Clarity library using the command ng add @clr/angular. However, I am encountering an error related to compatibility: 0 verbose cli [ 0 verbose cli 'C:\\P ...

Adapting body designs in Nuxt/Vue layout

Struggling to apply body styles in my Nuxt template, encountering issues. Attempting to utilize the beforeCreate, but facing an error: document is not defined. Desire to maintain SSR while adding styling to the body element. How can this be achieved? < ...

Display the selected value with JavaScript

Whenever I choose an item from a select dropdown that fetches data from an API, I then add the selected item's value to a table. Everything functions correctly except for when I click on addItem(), which adds the ID value of the selected item to the t ...

Creating a custom React hook in TypeScript to handle mouse events

I have been working on creating a custom hook in TypeScript/React, and I am looking to convert the code snippet below into a custom hook. Currently, I am passing handleClick to the onClick attribute in a div element to detect user clicks and route them to ...

What is the best way to create a dynamic URL linking to an external site in Angular 5?

When attempting to create a link like this: <a [href]="getUrl()">click me</a> getUrl() { return this.domSanitizer.bypassSecurityTrustUrl('http://sampleUrl.com'); } The link is not clickable. When hovering over the ...