Typescript - Defining types for a higher order function

I am currently utilizing the Okta react library found here:

https://github.com/okta/okta-oidc-js/tree/master/packages/okta-react
. Unfortunately, this library does not include type definitions.

To address this issue, I have created a .d.ts definition file with the following content:

declare module "@okta/okta-react"
. However, this library utilizes a higher order component in the form of:
import { withAuth } from '@okta/okta-react';
(more details can be found at https://github.com/okta/okta-oidc-js/tree/master/packages/okta-react#withauth)

My question is how to properly define this in my definitions file. Is the following declaration valid?

declare module "@okta/okta-react" {
    function withAuth(any): any
}

In addition, I have drafted an interface outlining the methods provided by withAuth, such as:

interface OktaWithAuth {
    /**
     * Returns true or false, depending on whether the user has an active access or id token.
     */
    isAuthenticated(): Promise<boolean>;
....
}

Any insights or assistance would be greatly appreciated. Thank you.

Answer №1

To enhance functionality, it is recommended to transform the withAuth function into a generic function that receives a component type as input and returns the same component type with modified props where the auth property is removed:


declare module "@okta/okta-react" {
  import React from 'react'
  function withAuth<P extends { auth: OktaWithAuth }>(comp: React.ComponentType<P>): React.ComponentType<Omit<P, 'auth'>>
  interface OktaWithAuth {
      /**
       * Determines if the user has an active access or id token.
       */
      isAuthenticated(): Promise<boolean>;

  }
}

You can test this setup in the following playground example: Playground Link

The implementation of Omit<P, 'auth'> ensures that the auth property is excluded from the P type using the predefined Omit helper type. Consequently, the returned component will inherit all original props except for the auth property added by the withAuth function.

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 Angular developers properly implement token refreshing in their applications?

Recently, I've been struggling with implementing a logic in my code. I have a specific requirement: Whenever there is a signed request (signed - means it has a JWT token for authenticated users) made to the API backend, the API backend may respond w ...

create an instance of the class provided as an argument

I wanted to design a system for creating different types of Plants (inspired by plants vs zombies) in an organized way. To simplify the addition of new plant Types, I aimed to make the cost and damage of each plant static so it could be set once for all Pl ...

Implementing validation logic on button click using TypeScript

I'm struggling to get my validation to work for empty fields using the method below. Can anyone provide some guidance or suggestions? Thanks. Here is my template: <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="nobottommargin ad ...

Improving the structure of a TypeScript switch statement

Looking for a more efficient way to implement a switch statement in TypeScript? Here is the current code snippet from a component: switch (actionType) { case Type.Cancel { this.cancel(); break; } case Type.Discard { thi ...

The identifier "id" is not a valid index for this type

The code snippet below demonstrates the similarities and differences between the functions addThingExample2 and addThing. While addThingExample2 directly uses the union type Things, addThing utilizes a generic parameter THING extends Thing. The expression ...

Develop a JSON parsing function for VUE reusability

Currently, I am iterating through an array in Vue that contains objects with strings nested within. These objects have various properties such as idType, type, user, visibility, seller, product, company, and additionalData. notifications: [ 0: { idTy ...

What is causing the failure of this polymorphic assignment within a typed observableArray in Knockout?

Consider a scenario where we have a class A and its subclass B. The goal is to assign an array of instances of class B to an array of instances of class A. While this works with normal arrays, the same operation fails when using ko.ObservableArray. import ...

Discovering the current date in Angular 8 by utilizing the form builder

Is there a way to automatically fill a form created with FormBuilder with the system's date and time when it is created, instead of the default date format? this.creationDate = moment().format(DATE_TIME_FORMAT); I want to update the creationDate fie ...

Learn how to utilize a Library such as 'ngx-doc-viewer2' to preview *.docx and *.xlsx files within the application

After 3 days of searching, I finally found a solution to display my *.docx and *.xlxs files in my angular application. The API returns the files as blobs, so my task was to use that blob to show the file rather than just downloading it using window.open(bl ...

An issue has occurred: [ERR_REQUIRE_ESM] You must utilize the import statement in order to load an

These are the snippets of code I'm working with: index.ts import { MikroORM } from "@mikro-orm/core" import { __prod__ } from "./constants"; import { Post } from "./entities/Post"; import microConfig from "./mikro-o ...

Creating a modularized NodeJs solution in Typescript by splitting it into multiple individual

I am looking to create a TypeScript Node.js solution divided into 3 sub-projects, similar to how a C# solution is split into multiple libraries. Each of these projects should have its own package.json. UI project package.json Infrastructure packa ...

What could be the reason for the click event returning undefined?

I can't seem to pass a date from a mat-option choice as it returns undefined when I try to log the event in the click method. How can I solve this issue? HTML <mat-drawer-content class="Font"> <mat-form-field appearance=& ...

What is the syntax for declaring a boolean or object type?

Is it possible to create a variable in TypeScript that can hold either true/false or an object of booleans? I'm still learning TS and would like some input on this syntax. variableA: { a: boolean, b: boolean } | boolean I found a workaround for now, ...

Each professional has their own unique workdays and hours, which are easily managed with the angular schedule feature

My schedule is quite dynamic, with professionals attending on different days for varying periods of time. Each professional has a different start and end time on their designated day. To see an example of this setup, you can visit the following link: Sche ...

The autocomplete feature in Atom is not functioning as expected

Autocomplete+ is included with the installation of Atom and is activated by default. I have noticed that when I am coding, no suggestions are appearing. What could be causing this issue? Do I need to adjust any files in order for Autocomplete+ to functio ...

UI-Router - issue with query parameters preventing arrays with only one item

My application utilizes UI-Router, specifically with a state named Widgets that includes a query parameter accepting an array of widgets: const widgetsState = { name: "widgets", url: "/widgets?{widgets:string[]}", component: Widgets, pa ...

Ways to resolve the issue of npm being unable to globally install typescript

While trying to globally install TypeScript using npm sudo npm install -g typescript An error occurs during the installation process with the following message: ENOENT: no such file or directory, chmod '/usr/local/lib/node_modules/typescript/bin/ ...

Spinning points about a center point

My goal is to rotate 4 points around a specific origin. Initially, the points appear in the correct position without any rotation. The code for this initial positioning is as follows: let origin = this.transform.position; for (let i in this._pointsOrig) { ...

Meeting the operator does not limit the variable type

Encountering issues with type narrowing using the satisfies operator. The goal is to specify that the name property of br should be of type "br": type RichTextCustomElement = { name: string; Button: React.ComponentType<any>; El ...

Having trouble retrieving data from redux toolkit using typescript

I've been diving into the world of Typescript by building a simple todo app using React, Redux-toolkit, and Typescript. One issue I encountered is when trying to access data from the store with useSelector. The retrieved object contains the desired va ...