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

The positioning of Material UI InputAdornment icons is located beyond the boundaries of the TextField input area

I am struggling to understand why my InputAdornment is not positioned correctly. There doesn't seem to be any style in my code that would affect the location of the icon within the TextField (such as padding or flex properties). Currently, the calen ...

Can you explain how I can showcase JSON object values within an Angular framework?

After fetching data through a REST API in Angular, I need to display only the "classLevelPermissions" in table format as shown in the .html file. .ts - async getclp(className: string) { debugger; this.clplist = []; this.className = className ...

Tips for concealing JavaScript files from the Chrome Developer Tools while using Next.js

Currently working on a project using Next.js. I've noticed that the utils/components are quite visible through the Chrome Developer Tools, as shown in this image: Is there a way to hide them from being easily accessible? And most importantly, is it s ...

Each time the page is reloaded, the animation's frames per second (fps

In my project, I have two main pages: 'index' and 'about'. The 'about' page includes a cool animation that you can check out here. The issue I'm facing is that when I navigate from the 'index' page to the &apos ...

What is the best way to verify both a null value and a length simultaneously within a template condition?

There is a data that can be null or an empty array, but the template should still be rendered if leaseApDto is not null or has a length greater than 0. I attempted to use the condition model.leaseApDto !== null || model.leaseApDto.length !=== 0, but they ...

Maximizing Angular and Require's Potential with r.js

I'm facing some challenges while setting up r.js with require in my Angular application. As I am new to AMD, solving this issue might be a simple task for someone experienced. However, I need to maintain the current directory structure as it allows me ...

Accessing JS code from HTML is not possible in React

Attempting to create a list using React, I have utilized the module found here: https://github.com/pqx/react-ui-tree I am currently testing out the sample application provided in this link: https://github.com/pqx/react-ui-tree/blob/gh-pages/example/app.js ...

Ways to modify an object similar to manipulating an array collection

Hey there, I've heard that iterating and editing objects (not arrays) is not the best practice. Is there a more efficient way to do it as easily as it can be done with an array of objects? Check out this link for reference new Vue({ el: '#app ...

Can the bottom border on an input textfield be removed specifically under the new character?

This is the new visual design I received: https://i.stack.imgur.com/kiQGe.png The label CLG is represented as a label, with the line being an input type=tel. Disregard the purple overlay... The designer has requested that I remove the border when a user ...

Unable to retrieve information from req.body, however able to retrieve data from req.params

I'm facing an issue with my code where I am not able to retrieve user data from req.body as it returns undefined. However, I can successfully access the required information from req.params. Can anyone provide guidance on how to resolve this issue? co ...

Using React MUI Select in combination with react-hook-form does not seem to be compatible with Cypress testing

Within my React application, I have implemented a form that includes a dropdown select. Depending on the option selected from the dropdown, different input fields are rendered. const [templateType, setTemplateType] = useState(""); const { regi ...

In Node.js, the `res.send()` function is called before the actual functionality code is executed

As a newcomer to node js, I am currently working on an app where I query the MySql DB and process the results using node js. One issue I have encountered is that if my initial query returns null data, I then need to perform another query and further proc ...

converting an angular object into a string representation

I stumbled upon this guide: . and it includes the following piece of code: import { Component } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl ...

Using jQuery, retrieve JSON data from a different domain URL, even if the JSON data is not well-structured

Currently, I am utilizing jQuery's ajax function to access a URL from a different domain which returns JSON data. During my testing phase, I've encountered an issue where the presence of multiple '&quot' strings within the JSON valu ...

In Javascript, swap out a particular colored region in an image with a different image

I've been scouring the internet in search of a solution to my problem, but it seems like I might not be looking in the right places. Imagine this image below, how can I replace the blue area with an image uploaded by the user? I'm struggling to ...

What is the method for inserting an object into a jsonArray in TypeScript?

I am trying to add an object to existing JSON data in TypeScript. I am new to TypeScript and have created an array variable called jsonArrayObject, which contains a boolean[] type. This jsonArrayObject holds a contactModel object with properties like fname ...

The passport authentication process is malfunctioning as there seems to be an issue with the _verify function

Having an issue and could use some assistance. I am currently implementing passport in my express application. While I am able to successfully register a user, I encounter an error when trying to log in. TypeError: this._verify is not a function at Str ...

Using Telerik Grid in MVC to access the object that is passed to ClientEvent functions on the Javascript side

Here's a challenging question I have. I'm working with a Telerik Grid that has some ClientSide Events: .ClientEvents(events => events .OnDataBinding("SetAjaxParameter") ) Within the SetAjaxParameter function, I am setting parameters for ...

Getting real-time comments after they have been submitted in ReactJS

Is it possible to dynamically display newly added comments in real-time without refreshing the page after submitting them to the database through an API? Here's a snippet of the code I currently have: const PostWidget = ({ post }) => { ...

Bot on Discord engaging in a gaming session

I recently developed a Discord bot with the status of ""playing a game"" and here is the code that I implemented: bot.on('ready', () => { console.log('Client is online!'); bot.user.setActivity('osu!'); Th ...