Leverage the key-value pairs in JSON to automatically suggest types within the function parameters

If we have data structured like this:

{
   "key1": "hardcoded string",
   "key2": "another hardcoded string",
}

Imagine a function with 2 parameters where the first parameter should refer to key1 and the second to its value.

For instance:

funcName('key1', 'hardcoded string')

The function operates as follows:

funcName(key, defaultValue) {
   return jsonData[key] || defaultValue
}

To enable auto-suggest for the JSON's keys, we can do something like this:

import data from './data.json'

type JsonData = typeof data

funcName<K extends keyof JsonData>(key: K, defaultValue: JsonData[K]) {
   return jsonData[key] || defaultValue
}

When attempting to pass the first parameter to funcName, suggested options include key1, key2. However, if we choose key1, we want the second parameter to suggest only 'hardcoded string'. Currently, the code provides type suggestions only for the first parameter but not the second.

Does anyone have any ideas on how to link the second parameter suggestion to the value of the first parameter?

Answer №1

To effectively narrow down the type of your JSON, consider using type assertion.

An example of how this could work:

import data from './data.json' as const;

The as const syntax is utilized for type assertion to prevent widening of types. This means that the type of data would be inferred as:

{
  "key1": "hardcoded string",
  "key2": "another hardcoded string"
}

However, it seems that this feature is not yet available based on discussions in Github threads.

Therefore, you may need to explicitly define the types one way or another.

You can either specify the type during import or create a declaration file for your JSON:

  1. Specify the type during import, or
  2. Create a declaration file for your JSON.

Here is an alternative method:

Start by creating a data.d.json.ts:

const data: {
  key1: 'hardcoded string';
  key2: 'another hardcoded string';
};

export default data;

Next, add the following key to tsconfig.json within compilerOptions:

"allowArbitraryExtensions": true

By setting allowArbitraryExtensions, TypeScript will refer to the new declaration file every time data.json is imported in a TS file. This approach ensures specificity in typing.

Your code should now resemble this structure:

https://i.stack.imgur.com/5XxbO.png

Another option is to utilize the first approach by defining the type directly:

type JsonData = {
  key1: 'hardcoded string';
  key2: 'another hardcoded string';
};

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

Trouble with implementing Ajax in Express and jquery

My app has a browse page where users can add items as owned or wanted. Currently, when adding an item it redirects back to the general /browse page. However, I want the page to not refresh at all. I'm attempting to achieve this with ajax, but as a beg ...

The performance of the React create app proxy agent in the package.json file seems to be sluggish,

In our react application (created as create-react-app), we have a proxy defined in the `package.json`. This proxy is used between the front-end (webpack) and back-end (express) during development, as outlined here. The section of the `package.json` where t ...

Bypass the typical practice of choosing input with javascript

I have a form with a select input that has a dropdown list of options. The requirement is that when the select input is clicked, I need to validate the form. If the form is incomplete, I want to prevent the select input from showing the option list. Howeve ...

The onload function in jQuery is not functioning properly when the page is refreshed

I'm just starting out with jquery and I have a simple project in mind. The idea is to have two pictures stacked on top of each other, but I want the page to start showing the second picture first (at a specific scroll point). Then as the user scrolls ...

Learn how to import MarkerClusterer from the React Google Maps library without using the require method

The sample provided utilizes const { MarkerClusterer } = require("react-google-maps/lib/components/addons/MarkerClusterer");, however, I would prefer to use the import method. I attempted using: import { MarkerClusterer } from 'react-google-maps/lib ...

Saving Pictures in Database Without Using jQuery

Hey there fellow developers, I'm currently immersed in a web project that involves reconstructing a social media platform similar to snapchat. To capture images, I am utilizing my webcam with JavaScript and saving the image data to a variable named i ...

Update article translation dynamically in Vue without needing to refresh the page

ArticleController public function index() { $locale = Lang::locale(); // $locale = Lang::getLocale(); $articles = Article::withTranslations($locale)->get(); return $articles; } resources/assets/js/pages/articl ...

Having trouble with managing state changes in a React application using Multiple Checkbox components from M

Trying to update the state of multiple checkboxes and then send a POST request. Visually, the checkboxes change, but the form data remains unchanged. Here is the code snippet: export default function AccountInformations(props) { // const { enqueueSnack ...

What is the best way to generate a fresh set of data from a search parameter?

I have received data from an API call that needs to be filtered. I am utilizing Redux instead of local state for this task. Below are the actions I have defined: import ActionTypes from '../constants/ActionTypes'; export const passengersDataAc ...

Steps to establish a connection with a remote MYSQL database using the actual IP address in Node.js

In my Nodejs file, I have set up the connection as follows. The issue arises when attempting to connect to the remote database on a server. module.exports = { host: '234.32432.32432',//this is an example IP address and not a real one. use ...

Mastering the Art of Utilizing Generic Typing to Access Objects

I am trying to find a way to access an object by class using generic typing. The issue I am encountering is that I am getting an error when trying to check if the locators contain an input field. type '{ form1: { item2: { checkbox: string; input: st ...

"npm is the go-to tool for managing client-side JavaScript code

As I delved into a document outlining the npm Developer Guide, a question sprang to mind. Is it within the realm of possibility to construct a web client application using javascript/css/html with npm at the helm? And if so, might there be examples avail ...

Tips for animating input width as the size value changes during an ajax query transformation

This is my JavaScript code: function updatePriceDisplay() { $.ajax({ url:"query.php?currency=<?=$currencycode;?>" }).done(function(data) { $("value").attr("value", data).attr("size", data.length - 2); }); } updatePriceDi ...

Identifying sluggish hardware or unresponsive browsers using JavaScript

My site features numerous CSS animations and transitions that run very slowly on specific browsers and older hardware. I want to avoid user-agent sniffing; is there a way to identify browsers or hardware configurations using JavaScript or a JS library, and ...

Versatile dataTable designed to seamlessly integrate with various data structures

My task is to develop an ajax dataTable that can handle a variety of data sources with different column names and data types. The challenge lies in the fact that I cannot predefine the column names or data types when coding the dataTable, as each data sour ...

Tips for properly formatting functional Vue components?

Below is a functional component that functions as intended. <template functional> <div> <input /> </div> </template> <script> export default { name: "FunctionalComponent" } </script> <styl ...

The asynchronous AJAX request is finished after the function call has been made. This can be achieved without using

I am in search of a solution that will allow an AJAX API call to finish before the containing function does without relying on jQuery as a dependency for just one REST call... After going through multiple solutions, all of which involve using jQuery, I ca ...

What is the process for embedding a NextJS app within a different website?

I'm searching for alternative methods to embed a React/NextJS application within another application. Currently, my solution involves using an iframe and specifying the source as the execution of the React/Nextjs application. I've explored diff ...

Discovering the data type from its textual representation

Is it possible for TypeScript to automatically determine the generic argument of assertTypeof based on the value of expectedType? I am looking for a way to use the function below without having to specify number multiple times. playable example type Typ ...

Storing data with jQuery

Looking to store objects in jQuery for events. Each event will have a date, title, and some text that needs to be stored in an array. Wondering if using a multi-dimensional array would be the best way to go so I can easily iterate through them with a count ...