Creating a Blank Mapped Type in TypeScript

Suppose I define a generic mapped type that associates keys with functions.

type SomeMappedType<T, R> = {
    [K in keyof T]: (...args: any[]) => R
}

This is then passed to my consuming function through an options type where it's optional.

type Options<T = any, R = any, P extends SomeMappedType<T, R> = SomeMappedType<T, R>> = {
    prop1?: P
}

I use this value and return the output type. In the code, if prop1 is undefined, it doesn't affect the output. However, the Output type returns a non-empty mapped type even in this case.

const test2: {
    [x: string]: any;
}

The output type looks like this:

type Output<T, R, P extends SomeMappedType<T, R>> = ResolveType<{ [K in keyof P]: ReturnType<P[K]> }>;

Is there a way for the default SomeMappedType<T, R> to convey that it essentially contains no keys? Essentially looking for a mapped type equivalent of an empty array []

You can check out this TypeScript playground link to see the issue

Thank you for your assistance!

EDIT:

The solution provided by @spender works well for the original example, which may have been too straightforward. Here's an updated example that demonstrates 2 different optional properties with distinct types contributing to the Output

Answer №1

Creating a mapping for the any type will result in a {[x:string]:...} mapped type. Therefore, your issue can be simplified with this example:

type A = {
    foo: "woo"
}
type M<T> = { [K in keyof T]: T[K] }
type MA = M<A>
//   ^? {foo: "woo";}
type MAny = M<any>
//   ^? {[x: string]: any;}

If there is no type to infer, the generic type T defaults to any. Consider defaulting it to {} instead of any:

type MEmpty = M<{}>
//   ^? {}

Therefore...

function someFunc<
    T = {}, 
    R = any, 
    P extends SomeMappedType<T, R> = SomeMappedType<T, R>>(
        options: Options<T, R, P>): Output<T, R, P> {
    //...
}

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

Issue Error: NG0201: NgControl provider not found within NodeInjector

My creativity has hit a roadblock and I'm looking for some help. I decided to use the Reactive Forms Module in Angular, so I imported it into my app.module.ts as shown below: import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ ...

Determine an expression based on a string in Typescript

Looking at the code snippet below, everything appears to be in order (view playground): type PathParam<T> = T extends `${string}:${infer U}` ? U : never; type Param = PathParam<"/post/:post_id">; // type Param = "post_id" ...

Encountering a problem while compiling the Next.js app

Whenever I execute the command npm run build for a Next.js project (built with React and TypeScript), I encounter the following error: Error: Missing "key" prop for element in array react/jsx-key This issue is specifically related to the following piec ...

Tips for enabling custom object properties in Chrome DevTools

In my typescript class, I am utilizing a Proxy to intercept and dispatch on get and set operations. The functionality is working smoothly and I have successfully enabled auto-completion in vscode for these properties. However, when I switch to the chrome d ...

Guide on inserting text fields or HTML content into a dropdown list using ng-multi-select in Angular 5

My current setup includes a multi-select drop-down with checkbox default. Now, I am looking to incorporate a text field next to the selected value. Initially, I attempted adding plain HTML code within quotes, but it did not yield the desired outcome. Then ...

Can an array be used to send an image in Ionic file upload?

I have an array of image URLs that looks like this: ["file:///data/user/0/io.ionic.starter/files/1542283317507.jpg",null, "file:///data/user/0/io.ionic.starter/files/1542283320931.jpg"] I am attempting to upload this array, named 'final', usin ...

Dynamic Assignment of Object Values Based on Enum Keys in Typescript

Check out this TS Playground for this piece of code. Dynamically Assigning Object Values Based on Enum Key I am attempting to achieve the following: in the interface iAnimals, each animal key in the enum Animals should have its associated interface value, ...

Bidirectional data binding in model-driven forms

Currently, I am working on a reactive form that includes fields for first name, last name, and display name. The goal is for the display name to automatically populate with the concatenated values of the first and last name. However, as I am still learning ...

Storing a variety of values within a formControl in Angular

I'm currently working on a form that involves managing an array of quantity materials in TypeScript. These materials can be added or removed from an inventory and are displayed in the HTML using ngFor. My goal is to allow the FormControl to accommodat ...

Freeform JSON Schema selector

Currently, I am working with JSON Schema and have a selection field with enumeration options. However, I would like to allow the user to input values manually if their desired value is not present in the selection. { '$id': 'https://exampl ...

What is the reason for Record accepting an array in TypeScript?

I'm puzzled as to why this code compiles in typescript. I've tried researching and checking the typescript documentation, but still can't find the answer. type RecType = Record<string, any> const arr: RecType = [1, 2, "three" ...

Lack of MaterialUI Table props causing issues in Storybook

Currently, I am utilizing MaterialUI with some modifications to create a personalized library. My tool of choice for documentation is Storybook, using Typescript. An issue I have encountered is that the storybook table props are not consistently auto-gene ...

Utilizing absolute import paths in Testcafe with Typescript causes the compiler to malfunction

When using absolute import paths in my test files, Intellij resolves correctly but the Testcafe compiler throws an error. Interestingly, no errors are thrown when using absolute paths within the application source files. I'm wondering what could be c ...

Navigating dropdown list items using the keyboard in TypeScript is a breeze

I've encountered a bug while working on my open-source project. The issue is with navigating the dropdown list items using the keyboard (arrow key/tab). I have implemented the keyboard-navigation logic, but I'm unsure of how to make it work corre ...

Prettier mandates that single-line if-statements without curly braces must be written on the same line

Having recently delved into the EsLint documentation, I've adopted the curly rule set to warning for instances of multiple or nested rows of statements within conditionals. "rules": { "curly":["warn", "multi-or-nes ...

Prisma: Incorrectly identifying existing items where the list contains any of the specified items

Within my Prisma model, I have a property designated to store a list of phone numbers in the format phones String[] @unique When making an API call with a model that may include one or more phone numbers, my goal is to locate any existing record where any ...

Error encountered in React TypeScript: Expected symbol '>' was not found during parsing

While transitioning from JavaScript to TypeScript, I encountered an error in my modified code: Error on Line 26:8: Parsing error: '>' expected import React from "react"; import { Route, Redirect, RouteProps } from "react-router ...

What is the most effective method for pausing execution until a variable is assigned a value?

I need a more efficient method to check if a variable has been set in my Angular application so that I don't have to repeatedly check its status. Currently, I have a ProductService that loads all products into a variable when the user first visits the ...

Contrast between categories and namespaces in TypeScript

Can you clarify the distinction between classes and namespaces in TypeScript? I understand that creating a class with static methods allows for accessing them without instantiating the class, which seems to align with the purpose of namespaces. I am aware ...

Determine in JavaScript if one date occurs exactly one week after another date

Currently, I am tackling a date comparison task for our application. The main objective is to compare the Start Date inputted by the user with the Operator/Region Effective Date, which signifies when a new list of product prices becomes valid. Our aim is t ...