TypeScript: Retrieve the data type of the provided object

Is there a way to create a function that receives a callback and returns the object returned by that callback? Here's an example of what I'm trying to achieve:

const my_object = my_function<A extends string, B extends boolean>
  ("my_object", true, () => ({
    helloWorld: () => {},
    greet: () => {},
    // etc...
  }));

This would allow me to call it like this:

my_object.helloWorld();
my_object.greet();

Currently, I have implemented the function as follows:

const my_function = <A extends string, B extends boolean>(Name: A, other:B, callback: () => Record<string, Function>) => {
  // some code for A
  // some code for B
  // then
  return callback();
}

Although the above code works fine, I am looking for a more strict approach. For example, I want TypeScript to catch runtime errors such as:

// @ts-expect-error
my_object.func_not_exist()

I do not want to manually declare types, like in the following example:

I don't want to do the following...

const my_function = <T>(callback: () => T): T => {
  return callback();
}

const my_object = my_function<"MyObject", true, { helloWorld: () => void; greet: () => void }>("MyObject", true, () => ({
 helloWorld: () => {},
  greet: () => {},
}))

p.s. the first two params are always required and cannot be removed. Is it possible to infer these types in this scenario?

In real cases, A is an interface extending an object, and B is the key of A, making them required for type-safety.

Answer №1

It seems like you're asking if this code snippet would work, right?

function my_function<T>(callback: () => T) {
  return callback();
}

const my_object = my_function(() => ({
  helloWorld: () => {},
  greet: () => {},
  // etc...
}));

The types of helloWorld, greet, and others in the callback function are automatically inferred by TypeScript when invoking my_function. So there's no need to redundantly define them twice.

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

How can you receive multiple lines of input in Python without utilizing list comprehensions?

Is it possible to take multi-line input and store it in a list without knowing the size beforehand? 1 2 3 4 > my_list=[] > size=int(input()) > for i in range(size): > my_list.append(int(input())) ...

Is there a way to set an antd checkbox as checked even when its value is falsy within an antd formItem?

I'm currently looking to "invert" the behavior of the antd checkbox component. I am seeking to have the checkbox unchecked when the value/initialValue of the antD formItem is false. Below is my existing code: <FormItem label="Include skills list ...

What is the best way to extract and display data from an API response object in my

{ "_metadata": { "uid": "someuid" }, "reference": [ { "locale": "en-us", ... bunch of similar key:value "close_icon_size" ...

What is the method for referencing a subtype within an established type?

When working with React-native, I came across a component called FlatList which includes a property known as ListHeaderComponent. My question is how to specify the type of this property without having to manually copy and paste the original type. Currentl ...

Tips for effectively overriding a method in typescript

Why is this.fullName appearing empty in the show() method? class Person { protected name: string = ""; constructor(name: string) { this.makeSir(name); } makeSir(name: string) { this.name = "sir" + name; } } class M ...

Angular 9: Chart.js: Monochromatic doughnut chart with various shades of a single color

My goal is to display a monochromatic doughnut chart, with each segment shaded in varying tones of the same color. I have all the necessary graph data and just need to implement the color shading. ...

How is babel-loader / tsc compiler able to distinguish between importing a package for its types only and for its functionalities?

Currently, I am integrating Typescript into my project. During this process, I made an interesting discovery. In the App.tsx file below, you will notice that I needed to use import firebase from "firebase/app" in order to access the firebase.ap ...

Error: React-Redux Provider is being called incorrectly

I am currently working on a small application to get familiar with using Redux Toolkit. My understanding of React/Redux mainly comes from an outdated Udacity course. Although the error message lists the top 3 reasons for this particular error, none of the ...

Issue with Angular Compilation When Importing Library Function into Web Worker

I am facing an issue with a web worker in Angular that used to function properly in the previous versions: /// <reference lib="webworker" /> import { ParseResult } from "papaparse"; import { readCSV } from '@fireflysemantics/ ...

Missing Directory Issue Upon Deploying Node.js App on Google App Engine

I have a Node.js web application built using TypeScript and Koa.js that I am looking to deploy on Google App Engine. The code has already been transpiled into JavaScript and is stored locally in the ./dist/src/ directory. Essentially, I only need to depl ...

Generate a collection of items through replication

Develop a function that takes specific input and generates an array of objects with a length of 10 by incrementing the ID of each duplicate object. The first object in the output array should have "visible" set to true, while all others should have it set ...

What are some creative ways to emphasize certain dates?

Is there a way to customize mui-x-date-pickers to highlight specific days from a Date array with green filled circles around them? I am using new Date and wondering how to achieve this effect. Below is the code snippet I am currently working with: <Dat ...

How can I ensure that TypeORM, Type GraphQL, Apollo Server, and Azure Functions work together seamlessly?

I have an Azure Function written in TypeScript that utilizes various technologies such as TypeORM, Apollo Server, and TypeGraphQL. The function involves creating resolvers for projects and tasks and establishing a database connection. import { createConne ...

Encountering intellisense problems while declaring or utilizing TypeScript types/interfaces within Vue.js Single File Component (SFC) documents

For my Nuxt 3 project, I am developing a component and attempting to declare an interface for the component props to ensure strong typings. Here is an example: <script setup> interface Props { float: number; } const props = defineProps<Props> ...

Toggle the presence of a string in an array with a checkbox

Currently, I am working on a user creation form for my Next.js front end project using TypeScript. The main goal is to allow an administrator to create new users by filling out a simple form which will generate a basic user object. Here is the structure of ...

Exploring the Wonderful World of Styled Components

I have a query regarding styled components and how they interact when one is referenced within another. While I've looked at the official documentation with the Link example, I'm still unclear on the exact behavior when one styled component refe ...

Create a custom function that scans an array and retrieves the item for a specific animal name if it exists within the array

As someone new to learning JavaScript, I have encountered a challenge that has left me stumped for quite some time. My task involves working with an array containing objects representing different animals, including details such as their species, names, ...

Issue with React/Next.js input field rejecting commas

I'm experiencing a problem with an input field in my React application that was developed using Next.js. The issue arises specifically when using an iPad device, where the input field behaves inconsistently when dealing with commas. When using deskto ...

How to extract a string value from an observable array in Angular2 NativeScript?

I inserted JSON data into an observable array. My goal is to extract only the address from ShowData, specifically as a string value based on its position. ShowData.ts: class ShowData{ constructor(public id:number, public name:string, public address:s ...

Creating a Custom Select Option Component with Ant Design Library

Is it possible to customize options in an antd select component? I have been trying to render checkboxes alongside each option, but I am only seeing the default options. Below are my 'CustomSelect' and 'CustomOption' components: // Cu ...