An error may occur when Typescript is instantiated with a varying subtype of constraint

I am encountering the "could be instantiated with a different subtype of constraint" error when trying to return a result that should match the expected type of a function. Despite removing irrelevant details, I'm struggling to pinpoint what exactly I'm doing wrong in my code snippet:

type User = { }

interface BasePageProps {
    user: User
}

type GetServerSidePropsResult<P> =
  | { props: P }

type PropsWithUser = <TProps extends BasePageProps>(
    callback: (user: User) => Promise<Omit<TProps, 'user'>>
) => Promise<GetServerSidePropsResult<TProps>>

export const testFunc: PropsWithUser = async (callback) => {
    const user = {}
    return { props: {
            user,
            ...(await callback(user))
        } }
}

Here is the exact error message I am facing:

'{ user: {}; } & Omit<TProps, "user">' can be assigned to the constraint of type 'TProps', however, it's possible that 'TProps' could be initialized with a different subtype of constraint 'BasePageProps'.

You can view this example on TS Playground here.

Why does the potential instantiation of TProps with a different subtype pose a problem? And how can I go about resolving this issue?

P.S.: Although these types are derived from Next.js, it is pertinent to note that the issue at hand is not specific to Next.js itself, hence please avoid linking its tag to this question.

Answer №1

Here is the correct signature for your function:

type PropsWithUser = <TProps extends BasePageProps>(
    callback: (user: User) => Promise<Omit<TProps, 'user'>>
) => Promise<GetServerSidePropsResult<BasePageProps & Omit<TProps, 'user'>>>

You can also simplify it by avoiding repetition:

type PropsWithUser = <TProps extends BasePageProps, TO = Omit<TProps, 'user'>(
    callback: (user: User) => Promise<TO>
) => Promise<GetServerSidePropsResult<BasePageProps & TO>>

To understand why the compiler raises an error, consider this example where a type TProps that extends

BasePageProps</code fails the function's result typecheck:</p>
<pre class="lang-javascript"><code>type User = { }

type AnotherUser = { a: string }

interface TProps {
    user: AnotherUser
}

interface BasePageProps {
    user: User
}

type Eq = TProps extends BasePageProps ? true : false // type Eq = true

type PropsWithUser = <TProps extends BasePageProps>(
    callback: (user: User) => Promise<Omit<TProps, 'user'>>
) => Promise<GetServerSidePropsResult<TProps>>

Check out this TS playground

Your function should return a result with type

Promise<{ props: { user: AnotherUser, ... } }>
, which it currently does not.

The error message states:

'{ user: {}; } & Omit<TProps, "user">' is assignable to the constraint of type 'TProps', but 'TProps' could be instantiated with a different subtype of constraint 'BasePageProps'

type User = { }

interface BasePageProps {
    user: User
}

type AnotherUser = { a: string }

interface ConcreteTProps {
    user: AnotherUser
}

// { user: {}; } & Omit<TProps, "user"> is assignable
// to the constraint of type TProps (i.e. BasePageProps)
const a: BasePageProps = { user: {} }

// However, 'TProps' could be instantiated with a different 
// subtype of constraint 'BasePageProps' (e.g. ConcreteTProps)
// This subtype cannot be assigned with { user: User }
const b: ConcreteTProps = { user: {} } // error

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

"An issue has been noticed with Discord.js and Discordx VoiceStateUpdate where the return

Whenever I attempt to retrieve the user ID, channel, and other information, I receive a response of undefined instead of the actual data import { VoiceState } from "discord.js"; import { Discord, On } from "discordx"; @Discord() export ...

Why am I encountering numerous errors while attempting to install Juice Shop?

My attempt to install the juice shop app from GitHub resulted in 63 errors showing up after running the command npm install. [riki@anarchy]: ~/juiceShop/juice-shop>$ npm install (Various warnings and engine compatibility issues) Multiple vulnerabilit ...

What methods are available to rapidly test Firebase functions?

While working with Typescript on firebase functions, I have encountered challenges in testing and experimenting with the code. Despite using the Lint plugin to identify errors without running the code, I am struggling to run the code and view the output. ...

Having trouble locating the name 'angular' in TypeScript error message

I have completed all the necessary settings, such as adding the typescript compiler in webstorm and installing tsd with npm. However, I am still encountering an error stating 'Cannot find name Angular'. tsd.json { "version": "v4", "repo": ...

Error code 70006 encountered in Typescript when attempting to reference a type as "any"

Currently, I am working on a React project that involves using TypeScript. This is quite new to me, and I have encountered a type error in one of my components... let dragStart = (e) => { let transferringData = e.dataTransfer.setData("text", e.tar ...

The FOR UPDATE clause is not functioning as intended in the SELECT query

I have been working on isolating my database to prevent multiple servers from reading or updating data in the same row. In order to achieve this, I have structured my query like so: SELECT * FROM bridge_transaction_state as bridge WHERE bridge.state IN (&a ...

I'm encountering difficulties utilizing ternary operators in TypeScript

I am struggling with ternary operators in TypeScript and need help understanding the issue. Please review the code below: const QuizQuestionContainer = ({ qa }: QuizQuestionContainerPropsType) => { const { question, option1, option2, option ...

I am experiencing issues with arrow pagination not functioning properly in TypeScript

My current project involves building a customer table with 10 customers displayed on each page. Additionally, there are arrows below the table to help users navigate and view more customers. Unfortunately, there seems to be an issue with the functionality ...

Traveling from one child route to another

I am encountering issues with route navigation between child routes, as I keep receiving "routes not found" errors. Despite trying multiple solutions like injecting and refreshing after child configuration, I still face difficulties in navigating to a spec ...

Comprehending the concepts of Observables, Promises, using "this" keyword, and transferring data within Angular with TypeScript

I am trying to figure out why I keep receiving the error message: "Uncaught (in promise): TypeError: this.dealership is undefined" when working with the authentication.service.ts file. export class AuthenticationService { private currentUserSubject: ...

Creating a Dynamic Table with Angular 6 - Automating the Population of Content Values

I have a task of populating a table with data from a JSON file. Take a look at the following code snippet: <table> <thead> <tr> <th *ngFor="let datakeys of listData[0] | keys">{{ datakeys }}</th> </tr> < ...

Issue with directive implementation of regex test as attribute - validations in typescript and angular

I am currently working on a project to create a module with custom validation directives. These validations are implemented using regular expressions (regex). The specific error I encountered is: Error: [$injector:unpr] Unknown provider: REG_EXPProvid ...

I encountered a function overload error while creating a component for the API service

As a developer venturing into API design with a backend server that handles client-side calls, I find myself grappling with Typescript, transitioning from a Java background. Encountering the error message "No overload matches this call" has left me seeking ...

Tips for troubleshooting the error "Cannot locate module mp3 file or its associated type declarations"

Seeking guidance on resolving the issue with finding module './audio/audio1.mp3' or its type declarations. I have already attempted using require('./audio/audio1.mp3'), but continue to encounter an error. ...

What steps should I take to resolve the issue of my endpoint failing to accept POST requests?

I am in the process of developing a customized API, with an endpoint that is specified as shown below: https://i.stack.imgur.com/sZTI8.png To handle the functionality for this endpoint, I have set up a Profiling Controller. Inside my controller directory ...

Issue ( Uncaught TypeError: Trying to access a property of undefined ('data') even though it has been properly defined

One of my custom hooks, useFetch, is designed to handle API data and return it as a state. useFetch: import { useState, useEffect } from "react"; import { fetchDataFromApi } from "./api"; const useFetch = (endpoint) => { const [d ...

How to Efficiently Remove Array Elements by Index in Typescript

What is the best way to remove an item by its index using Typescript? For example: let myArray = ['apple', 'banana', 'cherry', 'date']; // How can I delete the item at index 2? ...

How should I proceed if a TypeScript definition file that I am relying on is lacking a specific definition?

I have encountered an issue while using the React type definitions for my project. The focus method is missing on elements in the array returned by the refs property, which prevents me from getting a specific example to work. The compiler error states: pro ...

An issue occurred: Unable to access the 'login' property because of a TypeError

Setting up a login page and declaring an object in my login.ts file. public User: { login:"", senha:"", }; Utilizing [ngModel] to save values within the parameters of the object. <ion-item> <ion-label floating>Enter ...

Assign a variable with the value returned by a function

Can you help me with this question I have about validating fields with a function using AbstractControl? errorVar: boolean = false function(c: AbstractControl): {[key: string]: string } | null { // validation if 'test' is true or not goes here ...