Creating Typescript tuple function arguments using key-based approach

Currently, I am developing an API that utilizes tuples and I'm working on inferring the function arguments within these tuples.

To make things easier to understand, I have created a simple example showcasing what I am attempting to accomplish.

type InitializeType = ['initialize', (arg: string) => void]
type TerminateType = ['terminate', (arg: number) => void]
type RetrieveType = ['retrieve', () => void]

type ExpectedOutput = InitializeType | TerminateType | RetrieveType

// Expecting argument to be a string
const sampleTest: ExpectedOutput = ['initialize', (arg) => {
    console.log(arg)
}]

// Expecting argument to be a number?
const sampleTest1: ExpectedOutput = ['terminate', (arg) => {
    console.log(arg)
}]

// This is validated though..
const sampleTest2: ExpectedOutput = ['retrieve', () => {
    console.log(arg)
}]

Answer №1

By the end of December 2022, the autocompletion feature for discriminated unions of tuples is found to be less robust compared to discriminated unions of objects.

Contrast this with object-based unions:

type InitType = {name: 'init', fn: (arg: string) => void}
type DestroyType = {name: 'destroy', fn: (arg: number) => void}
type GetType = {name: 'get', fn: () => void}

type Expected = InitType | DestroyType | GetType

// arg is string
const test: Expected = {name: 'init', fn: (arg) => {
    console.log(arg)
}}

// arg is number
const test1: Expected = {name: 'destroy', fn: (arg) => {
    console.log(arg)
}}

// arg is not available
const test2: Expected = {name: 'get', fn: () => {
    console.log(arg) // Expected error
}}

An ongoing issue specifically targets your situation for improvement enhancing autocompletion for discriminated union as tuples #31977

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

Initializing start scripts in the package.json file

When launching my react app locally, I need to execute three commands: cd react-web npm run postinstall export REACT_APP_CUSTOMER_ENVIRONMENT=xxx npm start After running these commands, the application server starts on localhost:3000. For the start script ...

Trouble with formatting in React

I am presented with the following code snippet that I did not author: render: function () { if(this.state.loading){ return <div><span><i className="fa fa-spinner fa-spin"></i> Loading...</span></div& ...

Angular post request does not update the table

After displaying a table and a form on a page, I encountered an issue where the table does not update with new data when submitting the form. Even after refreshing the page, the new data is not reflected. As a newbie to Angular, I'm unsure of what exa ...

Find the maximum value in an array using TypeScript

I have a single-column array called n_fnc and I am trying to find the maximum value within it. However, my current approach does not seem to be working. let first = this.fncs.map(item => item.n_fnc); console.log("First",first); x= Math ...

Enhance the list visualization in Next.js by efficiently transferring data from child components

In my Next.js Page component, I have a setup similar to the following: export default function Index({ containers }) { const [containerListState, setContainerListState] = useState(containers); const updateContainerList = (container) => { contai ...

"Utilize Typescript to dynamically check data types during runtime and receive alerts for any potential

INTRODUCTION I am currently working with Angular 6. In Angular, typescript is utilized to allow you to specify the data type of your function's arguments: public fun1(aaa: number) { console.log(aaa); } If I attempt to call fun1 with a parameter ...

Is it important that the end date does not exceed the start date?

In my request, the end date cannot be later than the start date. For example, if the start date is 24/4/2017 and the end date is 23/4/2017, the search function should be disabled for the calendar date 23/4/2017. Only dates from 24/4/2017 onwards should be ...

Trigger the mousemove event only after the mouse click event has been activated

I need help with my code. I want an onmousemove event to occur when I click and move the mouse. Can someone assist me please? </head> <body> <img id="myImgId" alt="" src="Chrysa ...

Tips for transferring Google Maps place array data from Angular 5 TypeScript to HTML

I am new to Angular 5 and I am attempting to display nearby restaurant results using Google Maps in Angular 5. However, I am unsure of where to create the array in TypeScript and how to pass this array into the HTML when searching for "restaurant". I have ...

Retrieving selected item values in Angular 2 using ng2-completer

Recently, I decided to experiment with a new autocompleter tool that is unfamiliar to me: https://github.com/oferh/ng2-completer. I successfully imported it and it seems to be functioning properly. My current goal is to retrieve the values of the selecte ...

Intersection Observer API is not compatible with the functionality of the navigation bar

Having trouble with the Intersection Observer API. Attempting to use it to show a nav-bar with a white background fixed to the viewport once it scrolls out of view. Initially tested using console.log('visible') successfully to determine visibili ...

Creating a stunning horizontal bar chart with the react-d3-components framework

I am currently implementing a D3 chart using the react-d3-components library. So far, I have successfully generated a vertical bar chart. However, my specific requirement is to create a horizontal bar chart. import React from 'react'; import Reac ...

Sorting an array of objects in TypeScript may result in a type error

My data includes various categories, ages, and countries... const data = [ { category: 'Fish', age: 10, country: 'United Kingdom' }, { category: 'Fish', age: 9, country: 'United Kingdom' }, { category: ...

Maintain scroll position during ajax request

I am working on a single-page website that contains numerous containers. Each container's content is loaded dynamically via ajax, so they may not all be populated at the same time. These containers have variable heights set to auto. The website uti ...

Elevating Material-UI Drawer using makeStyles to a whole new level with styled-components

Currently working on a React app using TypeScript, Material-UI, and styled-components. While incorporating a SideDrawer with Material-UI Drawer component, I am transitioning my code from makeStyles to styled-components for easier maintenance. How ...

A ServiceWorker used a promise in FetchEvent.respondWith() that resulted in a non-Response value of 'undefined'. This caused an issue in browser-sync

There are times when my server encounters an error in the console: Failed to load ‘http://localhost:3000/browser-sync/socket.io/?EIO=3&transport=polling&t=Lm2wn4p’. A ServiceWorker passed a promise to FetchEvent.respondWith() that reso ...

How should a successful post request be properly redirected in React?

I am in the process of learning React and currently working on a small project. I have set up a NodeJS server to handle my requests, and now I am facing an issue with redirecting the user after a successful login. I successfully dispatch an action and upda ...

What is the best method for fetching the values of a select element in React.js?

I'm struggling to retrieve the value of a selected element in a dropdown list. I've tried debugging it, but haven't been able to get the value. I attempted to console log e.target.value, but unfortunately, it didn't work. Any thoughts o ...

What could be causing this JavaScript code not to run?

Help needed! I'm a student struggling to diagnose the issue in my code. Whenever I click the buttons, nothing happens at all. I've tried debugging by isolating each function, but still can't seem to figure it out. I've searched through ...

Chart.js is failing to display the chart when integrated with RequireJS

I have been attempting to display a chart using Chartjs and Requirejs, but unfortunately, it is not rendering properly and no error messages are being displayed. I am aware that I may be overlooking something simple due to fatigue, but I am unable to pinpo ...