Tips for creating a TypeScript function that is based on another function, but with certain template parameters fixed

How can I easily modify a function's template parameter in TypeScript?

const selectFromObj = <T, S>(obj: T, selector: (obj: T) => S): S =>  selector(obj) // some function from external library

type SpecificType = {a: string, b: number}
const selectFromSpecificObj: <S>(obj: SpecificType, selector: (s: SpecificType) => S) => S = selectFromObj

// Is there a way to simplify the last two lines like this? 
// Just to set T to {a: string, b: number}
// const selectFromSpecificObj: <S>(typeof selectFromObj<{a: string, b: number}, S>) = selectFromObj

Answer №1

Let's explore a method to achieve this. We establish a type that defines the selectFromObj function, where the object type T remains constant, while the return type S varies based on the arguments passed.

type ApplySelectorFunc<T> = <S>(obj: T, selector: (obj: T) => S) => S;

Subsequently, we can create modified references of selectFromObj that solely accept objects of a defined type once we apply the type ApplySelectorFunc with a specific value for T

type SpecificType = {a: string, b: number}

const selectFromSpecificObj: ApplySelectorFunc<SpecificType> = selectFromObj;

const good = selectFromSpecificObj({a: "", b: 1}, o => o.a)  // type = string
const bad = selectFromSpecificObj({a: ""}, o => o.a)  // error

Typescript Playground Link

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

Error: Unexpected token < occurs when using SVG require in Jest

I'm struggling to locate the source of this error. Currently, I am working with Typescript in React and using Jest and Enzyme for unit testing. Below is a snippet from my Package.json file: "scripts": { "start": "node server.js", "bundle": ...

A guide on dynamically showcasing/summoning icons in react by utilizing array data

QUESTION: 1 (SOLVED!) https://i.stack.imgur.com/1M1K7.png What is the best way to display icons based on an array of data codes? const data = [{ img: '01d' }, { img: '02d' }] if(data) { data.map((item) => ( <img src={`./ ...

The presence of a setupProxy file in a Create React App (CRA) project causes issues with the starting of react-scripts,

I have implemented the setupProxy file as outlined in the documentation: const proxy = require('http-proxy-middleware'); module.exports = function (app) { app.use( '/address', proxy({ target: 'http ...

rxjs - monitoring several observables and triggering a response upon any alteration

Is there a way to watch multiple observables and execute a function whenever any of them change? I am looking for a solution similar to the functionality of zip, but without requiring every observable to update its value. Also, forkJoin isn't suitable ...

Learn the best way to retrieve the highest number from a Array<String> in TypeScript or JavaScript

Can someone help me create a function in JS or TS that meets the following requirements? I am looking for a functional programming approach. ・Input type: Array(String) ・Output type: string or undefined Examples Input Result ["" ...

Unable to locate a type definition file for module 'vue-xxx'

I keep encountering an error whenever I attempt to add a 3rd party Vue.js library to my project: Could not find a declaration file for module 'vue-xxx' Libraries like 'vue-treeselect', 'vue-select', and 'vue-multiselect ...

Accessing data retrieved from an API Subscribe method in Angular from an external source

Below is the Angular code block I have written: demandCurveInfo = []; ngOnInit() { this.zone.runOutsideAngular(() => { Promise.all([ import('@amcharts/amcharts4/core'), import('@amcharts/amcharts4/charts') ...

Determine whether a many-to-many relationship involves a specific entity

I am currently working on developing an API for managing surveys. One challenge I'm facing is determining whether a specific user has moderation privileges for a particular survey. A many-to-many relationship has been set up between the two entities. ...

What is the best way to choose checkboxes from data that is passed dynamically?

https://i.stack.imgur.com/L3k59.png I am looking to add an edit feature to my application. When the user clicks on the edit option, they should be taken to a different page with the previously entered value displayed. While I have successfully retrieved ...

Encountering a Problem with vue-check-view Library in Typescript

After successfully declaring the js plugin with *.d.ts, I encountered an issue where my view was blank after using .use(checkView). Does the library vue-check-view support Typescript? Error: Uncaught TypeError: Cannot read property '$isServer' o ...

Struggling to locate the module in React Native with TypeScript configuration

Currently, I am in the middle of transitioning our react-native project from JavaScript to TypeScript. As I attempt to import old modules, I keep encountering the following error: Cannot find module 'numeral' Oddly enough, the 'numeral&apo ...

Steps to easily set up a date-range-filter in Angular 6!

I have put together a small StackBlitz project to showcase my current situation. My aim is to log all objects that fall within a specified date range. However, when I attempt to filter my objects, I am faced with an empty array as the result. I would like ...

Firestore - Insert new entries into an array in an existing document using Typescript

After retrieving data from Firestore using Firebase and implementing pagination function, I encounter an issue when attempting to add the new values to an array. Specifically, TypeScript raises an error message when I try to invoke the setState hook. int ...

Sharing a variable between an Angular component and a service

I am attempting to pass a variable from a method to a service. from calibration-detail.component.ts private heroID: number; getTheHeroID() { this.heroService.getHero(this.hero.id).subscribe(data =>(this.heroID = data.id)); } to step.service.ts I ...

Error: Idle provider not found in the promise

Currently, I am integrating ng2-idle into an AngularJS 2 application. After successfully including the ng2-idle package in the node_modules directory of my project, I attempted to import it into one of my components as shown below: Dashboard.component.ts: ...

Tips for removing the Y-Axis entirely from a CanavasJS chart

I'm working with a canvasJS chart and my goal is to completely hide the Y-Axis. I've managed to remove the Y-Axis line and title in this JSFiddle example. I came across these properties to hide the Y-Axis title and line, but I'm struggling t ...

What is the best approach for handling errors in a NestJS service?

const movieData = await this.movieService.getOne(movie_id); if(!movieData){ throw new Error( JSON.stringify({ message:'Error: Movie not found', status:'404' }) ); } const rating = await this.ratingRepository.find( ...

TypeScript - Minimize redundancy when defining types for a class and its constructor arguments

Here is a class structure I am currently using: class Person { id?: string = uuid(); name: string; constructor(data: Person) { _.merge(this, data); } } The 'uuid' function generates an id and '_' refers to loda ...

"NameService is not provided in Angular, please check your module

I've been struggling with loading a class into my Angular component. I've spent quite some time trying to figure out the solution, even attempting to consolidate everything into a single file. Here is what I have: Application.ts /// <referenc ...

Ways to access a property within an object using TypeScript

Can you help me extract the "attributes" array from this object and store it in a new variable? obj = { "_id": "5bf7e1be80c05307d06423c2", "agentId": "awais", "attributes": [ // that array. { "created ...