Weird occurrences in Typescript generics

function resizeImage<T extends File | Blob>(input: T, width: number, height: number): Promise<T> {
  return Promise.resolve(new File([new Blob()], 'test.jpg'))
}

Error:

(48, 3) TS2322:Type 'Promise' is not assignable to type 'Promise'. Type 'File' is not assignable to type 'T'.

Having trouble figuring out the issue.

Answer №1

The main idea is that your generic argument T represents a class that is inheriting from either File or Blob. The return type is specified as a simple Promise<File>, which cannot be assigned to the inherited type. The input argument's impact on the output is unclear, but the correct return type should be Promise<File>:

export function resize<T extends File | Blob>(input: T, w: number, h: number): Promise<File> {
  return Promise.resolve(new File([new Blob()], 'test.jpg'))
}

Answer №2

This approach worked in my case, but the output seems a bit odd to me

if (isFile(input)) {
    const file = new File([blob], input.name)
    resolve(file as T)
} else if (isBlob(input)) {
    resolve(blob as T)
}

excerpted from:

export
function adjustSize<T extends Blob | File>(input: T, width: number, height: number): Promise<T> {

    return new Promise((resolve, reject) => {

      const image = new Image()

        image.onload = () => {

            const canvas = document.createElement('canvas')
            canvas.width = width
            canvas.height = height

            pica.resize(image, canvas)
                .then((result) => pica.toBlob(result, input.type, 85))
                .then((blob: Blob) => {

                    if (isFile(input)) {
                      const file = new File([blob], input.name)
                      resolve(file as T)

                    } else if (isBlob(input)) {
                      resolve(blob as T)

                    }
                })
                .catch(err => reject(err))
        }

        image.src = URL.createObjectURL(input)

    })
}

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

Implementing the binding of components to another component post using forwardRef

I am looking to connect the Title and Body components with the Wrapper component. Previously, my component structure looked like this: import { FC } from 'react'; // binding required components const Title: FC<...> = () => {...} const ...

Error: The variable "document" is not defined in the context of NextJS TypeScript

Here is the import trace for the requested module: ./app/StarrySky.tsx ./app/resume/page.tsx ✓ Compiled in 425ms (711 modules) ⨯ app\StarrySky.tsx (9:4) @ document ⨯ ReferenceError: document is not defined Trying to set const vw equal to the ma ...

Guide on bringing in Typescript definition that exports a lone variable

The "@types/dd-trace" library defines a single variable called trace in the type definition for the "dd-trace" library. declare var trace: TraceProxy; export = trace; declare class TraceProxy extends Tracer { /** * Initializes the tracer. This s ...

What is the best way to extract the ID from an event in TypeScript?

HTML Code: <ion-checkbox color="dark" checked="false" id="1on" (ionChange)="onTap($event)" ></ion-checkbox> TypeScript Code: onTap(e) { console.log(e); console.log(e.checked); } I am trying to retrieve the id of the checkbox. H ...

Acquiring the appropriate type from a type object using generics in TypeScript

I am working with an enum export const trackingKeys = { Form: 'form', Video: 'video', } as const I also have a type that assigns a type property to each key export type TrackingPropertiesByKey = { [trackingKeys.Form]: { bar : num ...

Is it possible to incorporate regular React JSX with Material UI, or is it necessary to utilize TypeScript in this scenario?

I'm curious, does Material UI specifically require TypeScript or can we use React JSX code instead? I've been searching for an answer to this question without any luck, so I figured I'd ask here. ...

What are the steps to implement a Bottom Navigation bar in iOS and a Top Navigation bar in Android using NativeScript Angular?

For my project, I decided to utilize the tns-template-tab-navigation-ng template. I am currently working on creating a WhatsApp clone, and in iOS, it features a bottom navigation bar while in Android, it has a top navigation bar. I am looking for guidance ...

Tips for incorporating a svg file into your React project

I am facing an issue with my custom React, Typescript, and Webpack project. I am trying to import a basic .svg file and utilize it in one of my components. However, Typescript is throwing the following error: Cannot find module I have tried installing s ...

Gatsby no longer hosts the website locally during certain tasks

My React and Gatsby project runs smoothly when I use Yarn start, it builds everything and serves the project on http://localhost:8000. However, whenever I perform specific operations like going to a 404 page or opening Chrome Dev tools, it suddenly stops s ...

The Axios function is unable to read the 'Ok' value because of undefined properties

I suspect there is something missing in my argument, but I am attempting to call HttpStatusCode.Ok from the Axios Enum. Here is how I have implemented it: import { HttpStatusCode } from 'axios' console.log(HttpStatusCode.Ok) However, I encounte ...

Enforce numerical input in input field by implementing a custom validator in Angular 2

After extensive research, I was unable to find a satisfactory solution to my query. Despite browsing through various Stack Overflow questions, none of them had an accepted answer. The desired functionality for the custom validator is to restrict input to ...

I have noticed that my unit test case does not include coverage for the if statement

Here is the function I have in my TypeScript file: routeToIndividualPortal(sessionToken: string) { let redirectUrl = this.relayState; console.log("Pre-source-check Indivual URL : " + redirectUrl); let url = ""; if(redirectUrl.includes(this. ...

Having trouble with the .d.ts module for images?

I'm relatively new to Typescript and the only thing that's giving me trouble is the tsconfig.json. My issue revolves around importing images (in Reactjs) and them not being found: client/app/Reports/View.tsx:11:30 - error TS2307: Cannot find mod ...

Develop a cutting-edge TypeScript library that allows for seamless resolution of optional dependencies by the application

One of my recent projects involved creating a library that I published to a private npm repository. This library consisted of various utilities and had dependencies on other libraries, such as @aws-sdk/client-lambda. However, not all applications utilizin ...

Issue: ReactJS - $npm_package_version variable not functioning properly in build versionIn the current

After trying this suggested solution, unfortunately, it did not work for my specific case. The React application I am working on was initialized with CRA version 5.0.1 and currently has a version of 18.2.0. Additionally, the dotenv version being used is 1 ...

Exploring the SOLID Design Principles through TypeScript

Recently, I came across an intriguing article discussing the SOLID principles and delving into the concept of the Dependency Inversion Principle (DIP). The article presented an example to illustrate this principle using both an incorrect and a correct appr ...

Develop customizable enumerations for use in expandable interfaces

Situation: My objective is to devise a strategy for building scalable state machines in TypeScript using the TypeState library. TypeState offers a typesafe state machine for Typescript, which while not directly related to my current issue, serves as a good ...

Is there a way to ensure that the content of my modal dialog only displays once when it is opened?

While working with Chakra UI, I encountered a unique issue that I hadn't faced before with Material UI. The problem arises when using the Chakra UI modal dialog - all components inside it get rendered twice upon opening. Despite attempting to disable ...

class-validator: ensures the correct number of digits are present in numeric values

Seeking assistance on validating the number of digits for numeric values using class-validator. Specifically, I want my entity to only accept numbers with 6 digits for a certain property. For example: const user1 = new User(); user1.code = 123456 // should ...

Having issues with NGXS subscription not functioning properly when selecting a variable

Currently, I am working with Angular 11 and NGXS. One issue I am facing involves a subscription for a variable in the state. Here is the problematic subscription: @Select(state => state.alert.alerts) alerts$: Observable<any[]> ngOnInit(): void { t ...