Mapping Interface Types in Typescript

I am currently exploring the correct method to map Interface record value types to the appropriate function type.

function stringCompose(): string {
    return ''
}
function numberCompose(): number {
    return 0
}

interface Demo {
    stringVal: string;
    numberVal: number;
}
// mapping type something like <T = any> = (() => T)
type ComposeMapper<T = any> = any;

const builder: ComposeMapper<Demo> = ({
    stringVal: stringCompose,
    numberVal: numberCompose,
});

The concept is to ensure that when creating a builder, it verifies all Interface keys are present and also performs value mappings such as Interface "string" => requires "() => string" where compose functions should be applied. I previously attempted a similar setup, but encountered numerous never checks which resulted in poor performance while solving those issues. I believe there must be a simpler way to achieve this.

Answer №1

To tackle this issue, it appears that you must construct a mapped type based on the given interface.

For more information, visit this mapped types guide.

Access the TypeScript Playground through this TS Playground link.

function generateString(): string {
    return ''
}
function generateNumber(): number {
    return 0
}

interface Example {
    stringValue: string;
    numberValue: number;
}

type Generator<T> = {
    [K in keyof T]: () => T[K]
}

// Valid
const creator: Generator<Example> = ({
    stringValue: generateString,
    numberValue: generateNumber,
});

// Error
const creator1: Generator<Example> = ({
//    ~~~~~~~~ Property 'numberValue' is missing in type '{ stringValue: () => string; }' and is required in type 'Generator<Example>'.(2741)
    stringValue: generateString,
});


// Error
const creator2: Generator<Example> = ({
    stringValue: generateNumber,
//  ~~~~~~~~~ Type '() => number' cannot be assigned to type '() => string'.
    numberValue: generateNumber,
});

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

Strategies for setting the output value for a defined generic type

Is there a way to create a function that accepts optional properties common across different types, while also requiring specific properties based on the generic type passed in? type Diff<T, U> = T extends U ? never : T type DiffTypes<T, U> = ...

A guide on converting JSON to TypeScript objects while including calculated properties

I have a standard JSON service that returns data in a specific format. An example of the returned body looks like this: [{ x: 3, y: 5 }] I am looking to convert this data into instances of a customized TypeScript class called CustomClass: export class ...

Utilizing the power of the Google Calendar API with a service account in a Node.js environment

I have a vision to create an application with a specific feature set: Whenever there is a change in the user's Google calendar (an event is added, deleted, or edited), I want to receive updates with full event details. To achieve this, I understand ...

Struggling to get the bindings to work in my Angular 2 single-page application template project

I have recently started using the latest SPA template within Visual Studio 2017: https://blogs.msdn.microsoft.com/webdev/2017/02/14/building-single-page-applications-on-asp.net-core-with-javascriptservices/ The template project is functioning properly. ...

The argument of type 'NextRouter' cannot be assigned to the parameter of type 'Props' in this scenario

In my component, I am initializing a Formik form by calling a function and passing the next/router object. This is how it looks: export default function Reset() { const router = useRouter(); const formik = useFormik(RecoverForm(router)); return ( ...

When a TypeScript merged declaration composition is used with an extended target class, it fails to work properly

I have a TypeScript problem where I need to combine a class that has been extended with a few others. While searching for solutions, I came across an article outlining a pattern that I thought could be helpful: https://www.typescriptlang.org/docs/handbook ...

An issue has occurred: Failure to execute spawnSync PATH/target/node/node ENOENTNGCC. Please refer to the

Attempting to initiate my angular project using ./mvnw is resulting in an error when the build runs ng build --configuration development. The error message thrown reads as follows: Generating browser application bundles (phase: setup)... [INFO] /home/use ...

Converting Typescript library into a standalone global JavaScript file

Currently working on developing a Typescript library that follows this structure: https://i.stack.imgur.com/YyCHk.jpg This includes the following files: restApi.class.ts import { restApiOptions } from '../models/rest.options.model'; import { ...

How can I adjust the font size property for Material UI Icons through typing?

I put together the code snippet below, and I'm trying to define a specific type for the custom iconFontSize prop. Can someone guide me on how to achieve this? import { SvgIconComponent } from '@mui/icons-material' import { Typography, Typogr ...

How can I limit a type parameter to only be a specific subset of another type in TypeScript?

In my app, I define a type that includes all the services available, as shown below: type Services = { service0: () => string; service1: () => string; } Now, I want to create a function that can accept a type which is a subset of the Service ...

Improving the App() function in React and Typescipt

When working on my React/Typescript app, I encountered a challenge with the length of the code in one of the sections. Despite watching tutorials and searching for solutions, I couldn't find a clear way to refactor it. The specific issue is with refa ...

Using Visual Studio Code Build Tasks in Harmony

The documentation for Visual Studio Code includes examples of tasks.json configurations that allow for either typescript compilation or markdown compilation, but does not provide clear instructions on how to achieve both simultaneously. Is there a way to ...

Is there a way to attach a ref to a Box component in material-ui using Typescript and React?

What is the best way to attach a ref to a material-ui Box component in React, while using TypeScript? It's crucial for enabling animation libraries such as GreenSock / GSAP to animate elements. According to material-ui documentation, using the itemRef ...

Using TypeScript to work with JSON fields that include the '@' symbol

While working on an Angular project with TypeScript, I am facing a challenge of displaying certain JSON fields obtained from a POST request to the user. One of the fields begins with the '@' symbol, which is a reserved word in Angular causing th ...

What is the best way to implement debouncing for an editor value that is controlled by the parent component?

Custom Editor Component import Editor from '@monaco-editor/react'; import { useDebounce } from './useDebounce'; import { useEffect, useState } from 'react'; type Props = { code: string; onChange: (code: string) => void ...

When using AngularJS 2, the class identity is lost when resolving a Promise during fetching

SUMMARY: I'm encountering an issue where I am fetching Object instances instead of Org instances from my data in Angular 2. Is there a way to retrieve Org objects directly or is this the expected behavior? DETAILS: In my Angular 2 project, I have mod ...

Discover how TypeScript's strictNullChecks feature can help you identify null values with ease in your functions

Since Javascript often requires me to check if a value is `!= null && != ''`, I decided to create a function that checks for empty values: const isEmpty = (variable: any, allowEmptyString?: boolean): boolean => { return variable == null | ...

Can NODE_PATH be configured in Typescript?

Before, I worked on my React app with ES6 and used NODE_PATH='src' to import files starting from the src folder. However, since switching to Typescript, I've realized that NODE_PATH is not supported. After some investigation, I discovered th ...

Transferring information to a deep-level interface

I am currently working on creating an object that aligns with my interface structure. Success Story export interface ServiceDataToDialog { id: number, service: string, } constructor(private _dialogRef: MatDialogRef<DialogServiceTabletAddRowComp ...

The new data is not being fetched before *ngFor is updating

In the process of developing a "Meeting List" feature that allows users to create new meetings and join existing ones. My technology stack includes: FrontEnd: Angular API: Firebase Cloud Functions DB: Firebase realtime DB To display the list of meeting ...