Can type inference be used for overloaded functions with enum parameters?

Can type inference be performed using an overloaded function with an enum parameter? For instance, I am attempting to create a factory function where the return type is based on an enum value:

enum Colors {
  Red,
  Green
};

abstract class Box { };
class RedBox extends Box { };
class GreenBox extends Box { };

class BoxFactory {
  static createBox(color: Colors.Red): RedBox;
  static createBox(color: Colors): Box {
    switch (color) {
      case Colors.Red:
        return new RedBox();
      case Colors.Green:
        return new GreenBox();
    }
  } 
}

function makeMeABox(color: Colors) {
  // Argument of type 'Colors' is not assignable to parameter of type 'Colors.Red'
  return BoxFactory.createBox(color);
}

(playground)

If I generate a declarations file, the general overload does not appear. However, everything works as expected if the overload

static createBox(color: Colors.Red): RedBox;
is removed.

Answer №1

You are only missing one signature:

class PackageBuilder {
  static createPackage(size: Sizes.Large): LargePackage;
  static createPackage(size: Sizes): Package; // <--- THIS ONE
  static createPackage(size: Sizes): Package {
    switch (size) {
      case Sizes.Large:
        return new LargePackage();
      case Sizes.Medium:
        return new MediumPackage();
    }
  } 
}

Then:

let x = PackageBuilder.createPackage(Sizes.Large); // type of x is LargePackage
let y = PackageBuilder.createPackage(Sizes.Medium); // type of y is Package

(code in 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

Using a single Material Autocomplete input to handle two values within Angular

Looking to implement a search feature using Material's autocomplete that can filter by either user name or user ID. The current implementation is partially functional in this Stackblitz. When selecting a user name from the autocomplete options with a ...

"How can I display validation errors for email and fax in each row of loop items using Angular? Specifically working with Angular 8

In my Angular8 project with Bootstrap, I have created input fields dynamically from an array using a loop. When there is a validation error for the email or fax number input, the error is displayed. However, I noticed that if there is an error in the first ...

Getting the parent from a child in Typescript: Best Practices

Querying: In TypeScript, is it possible to retrieve a parent instance from a child instance? I am aware that casting a child into its parent is a method, however, the child's additional properties still exist in the parent, albeit concealed. Check o ...

Having trouble binding component property in VueJS with TypeScript?

Why is my component property not binding when I set the related component attribute to a value? Even when inspecting with Vue devtools or outputting the value into the HTML, it remains at the default value set on the component. I tried setting a string at ...

What is the proper way to utilize a function in C# that integrates with a window form using TypeScript?

I am currently working on a code that is in c# and utilizes a web browser. My goal is to convert the existing JavaScript code to Angular 7 and Typescript. Below is the c# code and the corresponding JavaScript code used to access the c# function from JavaS ...

Struggling to identify the memory leak in my Express.js Jest tests

Lately, I've been investing a considerable amount of time into identifying memory leaks within my Jest tests. While I have managed to resolve some issues, there is still a noticeable amount of memory leakage occurring from one test suite to the next. ...

Structuring a project with React and backend for sharing code

The organization of folders outlined in the structure below for a React frontend and Express backend is really appealing to me: root ├── backend | ├── node_modules | ├── public | ├── src │ │ └── Server.ts | ...

Using TypeScript to Add Items to a Sorted Set in Redis

When attempting to insert a value into a sorted set in Redis using TypeScript with code like client.ZADD('test', 10, 'test'), an error is thrown Error: Argument of type '["test", 10, "test"]' is not assigna ...

Difficulty in handling errors within an Express application

Hey there, I'm facing an issue with catching errors in my express.js application. The problem arises when the next function is called within the controller. For some reason, the error middleware does not execute as expected and I'm unsure why thi ...

Hey there! Is there a way to detect in React when the page is rendering due to a ctrl+shift+t command?

Is it possible to detect in React when a page is rendered using the ctrl+shift+t command? I am looking to identify the following scenario: The user closes the browser tab The user then reopens the tab by pressing ctrl+shift+t I want to be able to recogniz ...

Refine the category based on a specified key

Currently, I am in the process of developing a React Hook using TypeScript. In this hook, I am passing both a key and a value that will be associated with this key as arguments. My objective is to constrain the type of the value based on the specified key. ...

Retrieve a variety of outputs from computed properties in Vue

I have created buttons to select different dates (one for tomorrow and one for next week) with a function that calculates only business days. The 'tomorrow' button should display either 'Tomorrow' or 'Monday', while the ' ...

Transform a string into a class in Typescript/Angular

In my application, I've created a reusable modal popup component that takes a string as input and dynamically loads other components based on that input. This approach allows me to use the same modal popup component for multiple modals in the app inst ...

Encountered a bug in the findUnique function within the services of a Nest JS and Prisma project

I have a question about using Prisma with Nest. I keep encountering this error: src/modules/auth/auth.service.ts:28:63 - error TS2322: Type 'UserWhereUniqueInput' is not assignable to type 'string'. 28 const user = await this.prisma ...

Having trouble with importing GeoJSON from @types/ol package

I am currently working with the following files: tsconfig.json { "compilerOptions": { "lib": [ "es2019", "dom" ], "target": "es5", "module": "system", "allowSyntheticDefaultImports": tru ...

Utilizing TypeScript: Implementing a class within an object with explicit typing

I'm struggling with explicitly assigning a type in TypeScript from a class nested within an object (essentially a namespace): let obj = { hello: class { constructor: function () { console.log('hi'); } } } ...

TypeScript: restrict access to field to exclusive classes only

Here's an interesting dilemma I am facing. In my project, I adhere to the MVVM architecture pattern where I have separate Views for display logic and ViewModels for functional logic. The ViewModels contain methods and fields that can be accessed by ot ...

Converting JQueryPromise to Promise: A step-by-step guide

In my current project, there is a code snippet that produces a JQuery promise: const jqProm = server.downloadAsync(); I am interested in integrating this promise within an async function. I was thinking of creating something similar to the C# TaskComplet ...

What is the most effective method for eliminating leading and trailing slashes from a string - if they are present - while preserving the middle ones in TypeScript/JavaScript?

I have come across these variations of strings: some/dir/with/end/slash/ /some/dir/with/start/slash some/dir/without/any/start/or/end/slash /some/dir/with/both/slashes/ My goal is to remove both the start and end slashes if they exist, while keeping the ...

Navigating the complexities of integrating Rollup, ES modules, TypeScript, and JSX can be a challenging endeavor due to

Lately, I've been learning about the tools mentioned in the title. However, I've encountered some bumps along the way, so I'm turning to StackOverflow for help. My Requirements I need something like Rollup to pack my stuff For bare module ...