Tips for enabling type inference to function on a code snippet

Here is a simplified version of the code snippet:

export abstract class Scheduler<TPayload> {}

export interface EventKey<T> extends Symbol {}

export type SystemSpecification<TPayload> = (
  args: {
    /** The value provided by current scheduler tick */
    payload: TPayload;
  },
) => void;

export function defineSystem<TPayload>(
  system: SystemSpecification<TPayload>,
  scheduler: new () => Scheduler<TPayload>
) {
  // ...
}

const on = <TPayload>(eventKey: EventKey<TPayload>) =>
  class extends Scheduler<TPayload> {
    // ...
  };

const clickEvent = Symbol('clickEvent') as EventKey<{ zoo: 30 }>;

defineSystem(
  ({ payload }) => console.log(payload.zoo),
  on(clickEvent)
);

I expected the payload value to be inferred from the clickEvent type : {zoo: number}, however, I am getting an error stating: 'payload' is of type unknown

https://i.sstatic.net/gYDCa66I.png

Am I missing something? Is it possible to infer the payload from the clickEvent type?

Playground

Answer №1

Follow these steps to resolve the issue.

Create a new constructor type called SchedulerCtor and ensure that you use it as the type for the scheduler: argument in the defineSystem function and as the return type for the on function. Also, pay attention to the trailing comma — <TPayload,>



export abstract class Scheduler<TPayload> {}

export interface EventKey<T> extends Symbol {}

export type SystemSpecification<TPayload> = (
  args: {
    /** The value provided by current scheduler tick */
    payload: TPayload;
  },
) => void;

type SchedulerCtor<TPayload> = new () => Scheduler<TPayload>

export function defineSystem<TPayload>(
  system: SystemSpecification<TPayload>,
  scheduler: SchedulerCtor<TPayload>
) {
  // ...
}

const on = <TPayload,>(eventKey: EventKey<TPayload>): SchedulerCtor<TPayload> => {
  return class extends Scheduler<TPayload> {
    // ...
  };
};

const clickEvent = Symbol('clickEvent') as EventKey<{ foo: number }>;

defineSystem(
  ({ payload }) => console.log(payload.foo),
  on(clickEvent)
);

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

Transferring information to a navigated module using Angular2

I am currently facing a scenario where I have a component being loaded via routing, and my goal is to pass data from the parent component into this child component. How exactly can I achieve this task effectively? Parent Component Class export class Home ...

I am struggling to understand how to work with constrained generic functions

function calculateMinimumLength<T extends {length : number}>(arg1: T, arg2: T) : T { if (arg1.length >= arg2.length) { return arg2; } else { return arg1; } } let str = "Hello world"; const result0 = calculateMinimumLe ...

Issue with loading React Router custom props array but custom string works fine

I am facing an issue with my ReactTS-App where I pass a prop via Router-Dom-Props to another component. The problem arises when I try to use meal.food along with meal.name, or just meal.food alone - it doesn't work as expected. Uncaught TypeError: mea ...

Is there a way to incorporate the "Handoff to Human" feature in a Microsoft Teams bot app by utilizing the Teams Toolkit? Can this functionality be implemented using TypeScript?

Can someone assist me with figuring out how to incorporate the "handoff conversation to human agent mechanism" in my project using TypeScript, Microsoft Bot Framework, and Teams Toolkit? ...

Having trouble accessing functions within the webpack bundle

As someone new to the world of JS library development, I have embarked on a journey to achieve the following goals: Creating a library with TypeScript Generating a bundle using webpack5 Publishing the library to npm Utilizing the library in other projects ...

Encountering a snag when trying to load JavaScript within an HTML document

I encountered an error while trying to load an HTML file in the JavaScript console of the Brave browser. The error message reads: require.js:5 Uncaught Error: Module name "constants.js" has not been loaded yet for context: _. Use require([]) https://requir ...

Creating a unique custom view in React Big Calendar with TypeScript

I'm struggling to create a custom view with the React Big Calendar library. Each time I try to incorporate a calendar component like Timegrid into my custom Week component, I run into an error that says react_devtools_backend.js:2560 Warning: React.cr ...

Click on a link to open it in the current tab with customized headers

In my Angular project, I am attempting to open a link by clicking a button that redirects to the specified URL using the following code: window.open(MY_LINK, "_self"); However, in this scenario, I also need to include an access token in the header when t ...

Encountering a "is not a function" error in NextJS while attempting to import a custom hook

Exploring the world of NextJS, I am embarked on creating a responsive website starting with a navigation bar component. The goal is to ensure that it adapts seamlessly to different viewport dimensions. Let me walk you through my current folder structure: h ...

Transform a YAML document into either a JSON blueprint or a TypeScript structure

Currently seeking an efficient tool, preferably in Node JS, that can convert a YAML file from swagger into either a JSON SCHEMA or a typescript interface. The process I have used so far is: YAML->RAML->JSON SCHEMA->TYPESCRIPT interface STEP1: Co ...

Conceal multiple parameters within routing for added security

I have setup my Angular component with a button that triggers an event. Inside this event, I currently have: this.router.navigate('page2') While I am aware that query parameters can be passed inside the URL, I am faced with the challenge of pas ...

An error encountered while trying to utilize the npm convert-units package within an Ionic 4 application

In my Ionic 4 app, I am utilizing version 2.3.4 of the npm package called convert-units. To install this package in my Ionic 4 application, I used the CLI command: npm i convert-units --save However, upon importing the library with import { convert } fro ...

Encountering a 404 error with Angular 6 routing after refreshing the page when using an Nginx proxy

I currently have my angular application running within a docker container, exposed on port 83. Additionally, I have a separate spring-boot rest app running inside another docker container, exposed on port 8083. On the host server, there is an Nginx server ...

Tips for concealing text in ion-option ionic2

Is there a way to hide text within an ion-option? I'm looking to conceal or remove certain text from displaying in an ion-option without deleting the underlying data. This is important as I want users to be able to choose it. <ion-select [(ngModel ...

What steps should be followed to effectively incorporate Google Fonts into a Material UI custom theme for typography in a React/TypeScript project

Hey there, I'm currently working on incorporating Google fonts into a custom Material UI theme as the global font. However, I'm facing an issue where the font-weight setting is not being applied. It seems to only display the normal weight of 400. ...

Creating a personalized directive in Angular 2 that restricts input to only characters that adhere to a specified regular expression

I have successfully developed a directive that restricts any character from being typed in an input field if it does not match a specified pattern. import { Directive, Input, Output, HostListener, EventEmitter } from "@angular/core" @Directive({ select ...

The Ion-item-option button requires two clicks to activate

Within my ion-list, I have sliding items that are dynamically created using a for loop. Interestingly, when clicking on an item to navigate to another page, everything works fine. However, upon sliding an item, a button is revealed but it requires two clic ...

"Unlocking the potential: Exploring the power of keyof with

Currently, I am working with React Redux toolkit and keyof to specify that one element of my action payload should be the key of the type that my state is composed of. This allows me to update the properties of the state using a redux action. However, I am ...

When ngIf evaluates to false, Angular4's ng-content is constructed

I'm facing an issue with the new ng-content transclusion feature. To illustrate, let's consider a scenario where I have a component called my-component that performs some intensive operations in its ngOnInit() function (for now, just a console.l ...

TypeScript conditional return type: effective for single condition but not for multiple conditions

In my code, I have implemented a factory function that generates shapes based on a discriminated union of shape arguments. Here is an example: interface CircleArgs { type: "circle", radius: number }; interface SquareArgs { type: "square" ...