Properly typed tuple parameter for a function's return value

Is there a way to modify a function to return its value based on the type of the argument as a tuple? For instance, I need to adjust the getAll function so that it returns values based on an argument provided in a tuple.

type PathImpl<T, Key extends keyof T> =
  Key extends string
  ? T[Key] extends Record<string, any>
    ? | `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}`
      | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}`
    : never
  : never;

type PathImpl2<T> = PathImpl<T, keyof T> | keyof T;

type Path<T> = PathImpl2<T> extends string | keyof T ? PathImpl2<T> : keyof T;

type PathValue<T, P extends Path<T>> =
  P extends `${infer Key}.${infer Rest}`
  ? Key extends keyof T
    ? Rest extends Path<T[Key]>
      ? PathValue<T[Key], Rest>
      : never
    : never
  : P extends keyof T
    ? T[P]
    : never;

declare function get<T, P extends Path<T>>(obj: T, path: P): PathValue<T, P>;

const object = {
  firstName: "test",
  lastName: "test1"
} as const;

get(object, "firstName");

declare function getAll<T, P extends Path<T>>(obj: T, args: P[]): PathValue<T, P>;

const data = getAll(object, ['firstName', 'lastName'])
// how to produce the type: ['test', 'test1']

Playground

Answer №1

To effectively map the tuple that is passed in, you can utilize a mapped type. It is crucial to adjust the type parameter to accurately represent the tuple type.

type MapAllPaths<T, P extends Path<T>[]> = {} & {
  [K in keyof P ]: PathValue<T, P[K] & Path<T>>
}

declare function getAll<T, P extends [Path<T>] | Path<T>[]>(obj: T, args: P): MapAllPaths<T, P>;

Try it out on TypeScript Playground

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

Is it Beneficial to Combine jQuery with TypeScript in Angular 7?

Our school project team is venturing into the world of Angular and TypeScript, but we all admit to being newbies in this area. I've mainly focused on the design aspect of our project and left the coding to my teammates. However, I recently completed ...

When using TypeScript, my sorting function returns a value of 0 for all time values

I have been trying to sort this JSON data by date using the provided code, but it does not seem to work as expected. Below is a snippet of my JSON: { "StatusCode":0, "StatusMessage":"OK", "StatusDescription":[ { "id":"1", ...

Adding dynamic metadata to a specific page in a next.js app using the router

I was unable to find the necessary information in the documentation, so I decided to seek help here. My goal is to include metadata for my blog posts, but I am struggling to figure out how to do that. Below is a shortened version of my articles/[slug]/page ...

Applying specific data types to object properties for precise value identification in Typescript

I've been working on creating a dynamic settings menu in TypeScript using the following data: const userSettings = { testToggle: { title: "Toggle me", type: "toggle", value: false, }, testDropdow ...

Encountering a 404 error while attempting to test a contact form on a Next.js website using a local server

Trying to test a contact form in Next.js where the data is logged but not sent to the API due to an error. "POST http://localhost:3000/app/(pages)/api/contact/route.tsx 404 (Not Found)" Troubleshooting to identify the issue. [directory setup] ...

TS interfaces: Understanding the distinction between optional and mandatory properties

In this example, I am demonstrating TypeScript interfaces in a simple way: interface A: { id: number; email: string; } interface B extends A { login: string; password: string; } My goal is to have certain requirements when creating objects fr ...

What steps can be taken to fix error TS2731 within this code snippet?

I've been working through a book and encountered an issue with the code below. // This code defines a function called printProperty that has two generic type parameters function printProperty<T, K extends keyof T> (object: T, key: K) { let pro ...

Guide to specifying an explicit return type annotation for a recursive closure with JSDoc

In a project that utilizes vanilla JavaScript and type checking with tsc through JSDoc annotations, I have encountered a challenging use case. There is a function that returns another function, which may recursively call itself while also reassigning certa ...

What are some best practices for managing object-level variables in TypeScript and Vue.js?

Uncertain about the optimal approach, I am looking to create a component and leverage some object level variables. Consider the example below: import Vue from "vue" import * as paper from "paper" export default Vue.extend({ template: ` <d ...

Using Ionic to send email verification via Firebase

I have encountered an issue while attempting to send an email verification to users upon signing up. Even though the user is successfully added to Firebase, the email verification is not being sent out. Upon checking the console for errors, I found the f ...

The use of findDOMNode has been marked as outdated in StrictMode. Specifically, findDOMNode was utilized with an instance of Transition (generated by MUI Backdrop) that is contained

I encountered the following alert: Alert: detectDOMNode is now outdated in StrictMode. detectDOMNode was given an instance of Transition which resides within StrictMode. Instead, attach a ref directly to the element you wish to reference. Get more inform ...

Is the performance impacted by using try / catch instead of the `.catch` observable operator when handling XHR requests?

Recently, I encountered an interesting scenario. While evaluating a new project and reviewing the codebase, I noticed that all HTTP requests within the service files were enclosed in a JavaScript try / catch block instead of utilizing the .catch observable ...

Exploring the contrast between 'null' and an empty string as the fallback value in a TypeScript React component

Here is a Typescript interface that I am working with: export interface Page { description: string | null; } The description field in this interface can be either a string or null. I am curious about the difference between using null vs '' as ...

The code breaks when the lodash version is updated to 4.17.4

After updating lodash to version 4.17.4, I encountered an error in Typescript that says: TypeError: _.uniqBy is not a function Uncaught TypeError: _.split is not a function The code snippet in question is as follows: import * as _ from 'lodash&apo ...

How can I generate pure JavaScript, without using Typescript modules?

Take this scenario as an example ... index.ts import { x } from "./other-funcs"; function y() { alert("test"); } x(y); other-funcs.ts import { z } from "some-module"; export function x(callback: () => void): void { z(); callback(); } ...

Sign up for the completion event within the datetime picker feature in Ionic 2

How can I subscribe to the "done" event in Ionic2, where I want to trigger a function after selecting a date? <ion-icon class="moreicon" name="funnel"> <ion-datetime type="button" [(ngModel)]="myDate" (click)="getData()"></ion-datetime> ...

Each row in a table is filled with an array of data, with each column containing pdf

My goal is to split each associated element in every row of my PDF. Currently, the values are displayed below each column, as shown in the image below. packStruct = [] packEnergy = [] packDescriptionEnergy = [] packPrice = [] {text: 'Integration&apos ...

Module or its corresponding type declarations not found in the specified location.ts(2307)

After creating my own npm package at https://www.npmjs.com/package/leon-theme?activeTab=code, I proceeded to set up a basic create-react-app project at https://github.com/leongaban/test-project. In the src/index.tsx file of my react app, I attempted to im ...

The error message TS2304 is indicating that the name 'Set' cannot be found in electron-builder

I am trying to utilize the AppUpdater feature in electron-builder for my Electron Application. Upon importing the updater in my main.ts file: import { autoUpdater } from "electron-updater" An error is triggered when running the application: node_module ...

Using the ngFor directive, parent and child components can establish communication even with empty arrays

I am working on passing data from a parent component to a child component using the ngFor directive. However, I am facing an issue when some arrays have no length, as I need to indicate to the child component that the array is empty. How can I achieve this ...