Import a JSON file into TypeScript declaration files (*.d.ts)

I am currently working on a declaration file where I need to establish a global type that is specifically tied to a predetermined list of string phrases. These string phrases are part of property keys within an object located in a JSON file.

I have a couple of questions:

  1. Can I import a JSON file into a declaration file and manipulate it using basic functions like Object.keys and Array.map?
  2. Additionally, can I utilize a JavaScript array of strings to define a type in TypeScript?

Let's delve into some code example for better clarification.

Imagine we have the following JSON file named data.json:

{
  "someList": {
    "#key1": {"a": 1, "b": 2},
    "#key2": "some value",
    "#key3": 1234
  }
}

My goal is to create the declaration file global.d.ts as shown below:

import data from './data.json';

declare global {
  type AllowedKeys = Object(data.someList).map(key => key.substr(1));
}

In essence, I need the type to be dynamically defined based on the contents of the JSON file, such as:

type AllowedKeys = "key1" | "key2" | "key3";

Any assistance or pointers on this matter would be greatly appreciated.

Answer №1

UPDATE: Now, with template string literals, you can extract a substring starting from a specified character like this:

import data from "./data.json";
export type AllowedKeys = keyof typeof data["someList"] extends `#${infer K extends string}` ? K : never;
// This is similar to
// export type AllowedKeys = "key1" | "key2" | "key3"

In TypeScript, you can let the compiler infer a type based on JSON data.

import data from "./data.json";

export type AllowedKeys = keyof typeof data["someList"];
// This is equivalent to
// export type AllowedKeys = "#key1" | "#key2" | "#key3"

The resulting d.ts file will appear as follows:

import data from "./data.json";
export declare type AllowedKeys = keyof typeof data["someList"];

Currently, there are limitations in manipulating string literals within TypeScript (e.g., removing the #).

For more information, refer to these GitHub issues :

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

Ways to manage an rxjs observable reaction that may potentially have no data?

Currently, I am working with Angular2 and Ionic2 using typescript and have a requirement to manage responses from the backend service. The response may either be empty with http status 200 or it could be a json object containing an error message property ...

loop through the array of objects using ng-repeat in Angular

I am facing an issue where I need to display the data fetched from a service in my application. The service response is as follows: Object {resultado:array[2], mensaje: "4 personas `necesita tu ayuda"} Currently, the "resultado" field contains an object ...

The scroll animation feature was not functioning properly in Next.js, however, it was working flawlessly in create react app

I recently transitioned a small project from Create React App (CRA) to Next.js. Everything is working as expected except for the scroll animations in Next.js, which are not functioning properly. There are no errors thrown; the animations simply do not occ ...

Retrieving the value that is not currently selected in a mat-select component

In my mat-table, there is a mat-select component displayed like this: <mat-select multiple placeholder="{{element.name}}" [(value)]="selectedCol" (selectionChange)="selectionChange($event)" [disabled]="!selection.isSelected(element.id)"> & ...

The unit tests are not triggering the execution of setTimeout

Currently, I am developing a project in TypeScript and for unit-tests, I am utilizing QUnit and sinonjs. One of the functions within my code dynamically renders UI elements. I need to retrieve the width of these dynamic elements in order to perform additio ...

Hidden back navigation strategy in AngularJS 2 with location strategy

After creating a custom LocationStrategy to disable browser location bar changes, I am now looking to integrate smaller apps into various web pages without affecting the browser's location. While navigation works smoothly with this new strategy, I am ...

Converting Json string to a Set of objects in Java

Despite searching for two days, I haven't been able to find a solution to my problem with parsing a json string. Here is the json string: [ { "firstName": "dan", "lastName": "cohen", "email&qu ...

Testing in Jasmine: Verifying if ngModelChange triggers the function or not

While running unit tests for my Angular app, I encountered an issue with spying on a function that is called upon ngModelChange. I am testing the logic inside this function but my test fails to spy on whether it has been called or not! component.spec.js ...

Transforming Excel data into JSON format using ReactJS

Currently, I am in the process of converting an imported Excel file to JSON within ReactJS. While attempting to achieve this task, I have encountered some challenges using the npm XLSX package to convert the Excel data into the required JSON format. Any as ...

Is there a way to assign API data as inner HTML using Lit?

Need help setting inner html of html elements with a get request Any suggestions on how to achieve this? import { LitElement, html, css } from "lit"; import { customElement } from "lit/decorators.js"; import axios from "axios" ...

I am facing an issue with my useFetch hook causing excessive re-renders

I'm currently working on abstracting my fetch function into a custom hook for my Expo React Native application. The goal is to enable the fetch function to handle POST requests. Initially, I attempted to utilize and modify the useHook() effect availab ...

Leverage the power of Python to extract and store various JSON data entries into an SQLite

I'm trying to find a subtle way to import a JSON array (i.e. [] with {} objects inside) into an sqlite database. At the moment, I am facing difficulty in figuring out how to phrase INSERT into MYTABLE (col 1, col2, ...) this datarow in this jsondata ...

Failed to decipher an ID token from firebase

I'm feeling extremely frustrated and in need of assistance. My goal is to authenticate a user using Google authentication so they can log in or sign up. Everything worked perfectly during development on localhost, but once I hosted my app, it stopped ...

Guide to using a JSON WCF service in C#

I have a JSON web service. The address is provided. The WSDL code includes the following: <wsdl:binding name="BasicHttpBinding_iBOER" type="tns:iBOER"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" /> - <wsdl:operation n ...

Exploring TypeScript's Classes and Generics

class Person { constructor(public name: string) {} } class Manager extends Person {} class Admin extends Person {} class School { constructor(public name: string) {} } function doOperation<T extends Person>(person: T): T { return person; } ...

Get JSON information based on index position

Whenever I need to generate JSON data for a shopping cart, I rely on PHP's json_encode() method: { "6cb380f1bfbcd7728be7dfbf2be6bad4": { "rowid": "6cb380f1bfbcd7728be7dfbf2be6bad4", "id": "sku_131ABC", "qty": "4", "price": "35.95", ...

Is it possible to continuously re-render a React Functional Component with Axios and useState/useEffect?

Seeking assistance with creating a React Functional Component using Typescript to fetch data from an API and pass it to another component. However, encountering the error message "Error: Too many re-renders. React limits the number of renders to prevent an ...

Using Regular Expressions to Eliminate JSON Node in SQL Server

I'm faced with a challenge involving a database table where JSON data was incorrectly updated in one of the columns. I have identified the pattern required to remove the incorrect node from the JSON string. My task is to create a regex expression tha ...

Adjusting the prototype of a JavaScript object in real-time

Is there a way to dynamically change object prototype in JavaScript in order to fully recover an object previously saved using JSON, including its behavior? Currently, one solution is to create a new object and copy the data from the JSON-recovered object ...

Managing errors with the RxJS retry operator

I'm facing an issue with my RxJS code where I need to continuously retry a data request upon failure while also handling the error. Currently, I am using the retry operator for this purpose. However, when attempting to subscribe to the retry operator ...