How to verify the existence of an object property in typescript

I am dealing with a queryParams object that I need to use to query the database based on its properties. However, I am unable to determine which parameters it contains. I attempted to utilize

find(queryParameters: object = { limit: 50 }){
if (queryParameters.hasOwnProperty("limit")) {
   console.log( queryParameters.limit)
}
}

but I keep receiving an error stating that Property 'limit' does not exist on type 'object'. Is there a solution to this issue?

Answer №1

Let's say you have a query parameter class structured like this:

class QueryParam {
    // offset is optional
    // limit has the default value of 50
    constructor(public offset?: number, public limit: number = 50) {}
}

function checkParameters(queryParams: QueryParam){ 
    // ensure that the limit is defined (using the default value if not)
    if (queryParams.limit) {
        console.log(queryParams.limit)
    } else {
        console.log("no queryParams provided, falling back to default...")
    }
    // check if the offset is defined
    if(queryParams.offset) {
        console.log(queryParams.offset)
    } else {
        console.log("offset not found")
    }
}

checkParameters(new QueryParam())
// assume offset = 20
checkParameters(new QueryParam(20))

This should address your inquiry, link to the 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

Subclass method overloading in Typescript

Take a look at this example: class A { method(): void {} } class B extends A { method(a: number, b: string): void {} } An error occurs when trying to implement method() in class B. My goal is to achieve the following functionality: var b: B; b.met ...

How can I dynamically insert a variable string into a link tag using React and TypeScript?

I am just starting out with javascript and typescript, and I need to generate a link based on certain variables. I am currently facing an issue trying to insert that link into <a href="Some Link"> Some Text </a> Both the "Some Text" and "Som ...

A function's behavior will vary depending on whether it is a property of an object or not

I've been observing some peculiar behavior: In a typical scenario, TypeScript usually raises an error when an object contains too many keys, like this: type Foo = { a: string; } const a: Foo = { a: "hello", b: "foo" // Ob ...

Differentiating functions in Typescript through method overloading by inferring the second argument's type based on the first argument's

Looking to implement method overloading in Typescript with stricter type checking for method invocation based on different arguments. I am encountering an error: 'props' is possibly 'undefined'. This is the code that is causing the e ...

Error message in Typescript with React: "The type 'ComponentClass<StyledComponentProps<{}>>' cannot be assigned to type 'typeof MyComponent'"

Currently experimenting with integrating the Material UI 1.0 (beta) @withStyles annotation into a React component. The documentation provides a JavaScript example (), however, it results in a compilation error when using Typescript. Despite the error, the ...

The TypeScript namespace does not exist or cannot be located

Currently, I am working on coding in TypeScript. The specific code pertains to an Angular 2 application, but the main focus of my inquiry lies within TypeScript itself. Within my project, there are certain files that contain various models, such as the exa ...

When utilizing Ionic Firebase, the user profile saved in the sidemenu is stored using the Events class. However, the saved profile disappears as soon as

Hello there. I am currently working on displaying my user's information in the sidemenu, and after some research, I found that using the Events class might solve this issue. However, I have noticed that the data saved in subscribe gets destroyed whene ...

Are the module options in tsconfig referring to the 'SystemJS' module loader system?

When configuring a tsconfig.json file, one option that can be entered as the value for the compilerOptions 'module' property is: System This results in the following format: { "compilerOptions": { "module": "System", ... Is the &ap ...

Syntax for nested arrow functions in TypeScript

const fetchAsyncData = (input: { value: string }): AppThunk => async (dispatch) => { try { const fetchedData = await getData({ input.value }); } catch (error) { console.log(error); } }; An error message is displayed stating "No value ...

What is the best way to utilize the `Headers` iterator within a web browser?

Currently, I am attempting to utilize the Headers iterator as per the guidelines outlined in the Iterator documentation. let done = false while ( ! done ) { let result = headers.entries() if ( result.value ) { console.log(`yaay`) } ...

What is the best method for saving information from a service to a class or interface in Angular 2?

I am currently in the process of developing a new web application and I am fairly inexperienced with Angular2. I am encountering an issue with one of my components that acts as a form for users to update their data. The problem lies in accessing specific ...

Using TypeScript, a parameter is required only if another parameter is passed, and this rule applies multiple

I'm working on a concept of a distributed union type where passing one key makes other keys required. interface BaseArgs { title: string } interface FuncPagerArgs { enablePager: true limit: number count: number } type FuncArgs = (Fu ...

How is babel-loader / tsc compiler able to distinguish between importing a package for its types only and for its functionalities?

Currently, I am integrating Typescript into my project. During this process, I made an interesting discovery. In the App.tsx file below, you will notice that I needed to use import firebase from "firebase/app" in order to access the firebase.ap ...

Angular 2 Typescript: Understanding the Structure of Member Properties and Constructors

I am currently exploring a project built with Ionic 2, Angular 2, and Typescript, and I find myself puzzled by the way member properties are being set. In the code snippet below, I noticed that Angular automatically injects dependencies into the construc ...

Modifying the Iterator Signature

My goal is to simplify handling two-dimensional arrays by creating a wrapper on the Array object. Although the code works, I encountered an issue with TypeScript complaining about the iterator signature not matching what Arrays should have. The desired fu ...

Angular Tips: Mastering the Art of Setting Multiple Conditions using ngClass

Currently, I am in the process of developing my own UI library by utilizing angular and Tailwind. However, I have encountered a challenge while using ngClass : <button [ngClass]="{ 'px-4 py-2 text-sm': size === 'md', ...

"Can you guide me on how to invoke a parent function from retryWhen in Angular

I'm struggling to figure out how to execute a function from retryWhen and then call the parent function once retryWhen is done. Any ideas on how I can achieve this? getStatuses(statusesType: string[]): Observable<IStatus[]> { let body ...

What is the best way to dynamically include various properties in an object type depending on a generic union?

Consider the following union type: type Union = "a" | "b"; Is there a way to add multiple new keys to an object type with conditions? Adding one key with a condition is straightforward: type Condition<T extends Union> = { [K in ...

Animated drop-down menu in Angular 4

I recently came across this design on web.whatsapp.com https://i.stack.imgur.com/ZnhtR.png Are there any Angular packages available to achieve a dropdown menu with the same appearance? If not, how can I create it using CSS? ...

How can I effectively link data to an Angular Material dropdown in Angular 5?

Essentially, I am updating a user profile with user information that needs to be bound to the corresponding fields. this.editOfferprice= new FormGroup({ xyz : new FormControl(xxxx,[]), xxx: new FormControl(xxxx,[Validators.required]), ...