Building a TypeScript JSON API without the need for the "any" data type

It seems like creating a generic JSON type interface in TypeScript may be challenging due to the return type of the native JSON.parse function being any. Despite this, I have been exploring ways to achieve this and found a solution on GitHub that is very close:

type JSONValue = boolean | number | string | JSONObject | JSONArray

interface JSONObject {
  [k: string]: JSONValue
}

interface JSONArray extends Array<JSONValue> {}

const json: JSONObject = {}

console.log(json.gray[9])

However, this solution fails to compile in strict mode with the following error message:

~ ❯❯❯ tsc --strict test.ts
test.ts(11,13): error TS7017: Element implicitly has an 'any' type because type 'JSONValue' has no index signature.

It appears that even though JSONObject and JSONArray have index signatures, the union type JSONValue does not accept one according to the compiler. I am interested to know if there is a way around this limitation for my own learning. Considering that the GitHub issue dates back to 2015, it's possible that TypeScript has evolved since then.

Any insights or advice from experienced TypeScript developers would be greatly appreciated!

Answer №1

interface JsonObject {
  [key: string]: JsonValue;
}

type JsonValue =
  | null
  | boolean
  | number
  | string
  | JsonValue[]
  | JsonObject;

const stringify = (subject: JsonObject) => {};

stringify({
  foo: 'bar',
});

stringify({
  // @ts-expect-error
  foo: () => {}
});

Click here for more details

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

Utilizing Next.js to create a Higher Order Component (HOC) for fetching data from a REST API using Typescript is proving to be a challenge, as the

In my withUser.tsx file, I have implemented a higher order component that wraps authenticated pages. This HOC ensures that only users with a specified user role have access to the intended pages. import axios, { AxiosError } from "axios"; import ...

Creating applications with Angular2 and TypeScript is possible even without utilizing NPM for development

I've seen all the guides recommend installing npm, but I'm determined to find an alternative method. I found Angular2 files available here, however, none of them are in TypeScript code. What is the best course of action? Do I need Angular2.ts, ...

The Next.js template generated using "npx create-react-app ..." is unable to start on Netlify

My project consists solely of the "npx create-react-app ..." output. To recreate it, simply run "npx create-react-app [project name]" in your terminal, replacing [project name] with your desired project name. Attempting to deploy it on Netlify Sites like ...

When ts-loader is used to import .json files, the declaration files are outputted into a separate

I've encountered a peculiar issue with my ts-loader. When I import a *.json file from node_modules, the declaration files are being generated in a subfolder within dist/ instead of directly in the dist/ folder as expected. Here is the structure of my ...

`It is important to note that in Tailwind CSS, `h-8` does not supersede `h-4

I developed an Icon component that looks like this: import { IconProp, library } from "@fortawesome/fontawesome-svg-core"; import { far } from "@fortawesome/free-regular-svg-icons"; import { fas } from "@fortawesome/free-solid-svg- ...

Trouble with implementing a custom attribute directive in Angular 4 and Ionic 3

Hello, I am currently working on implementing a search input field focus using a directive that has been exported from directives.module.ts. The directives.module is properly imported into the app.module.ts file. However, when attempting to use the direc ...

Retrieving the row value of a checkbox in an Angular table

I'm facing a challenge where I have a table with three columns, one of which is a checkbox. Here is an image for reference: https://i.sstatic.net/4U6vP.png Here is the code snippet: <div nz-row> <nz-table nz-col nzSpan="22" [nzLoading] ...

Access an external URL by logging in, then return back to the Angular application

I am facing a dilemma with an external URL that I need to access, created by another client. My task is to make a call to this external URL and then return to the home page seamlessly. Here's what I have tried: <button class="altro" titl ...

Encountering issues with accessing properties of undefined while chaining methods

When comparing lists using an extension method that calls a comparer, I encountered an error. Here is the code snippet: type HasDiff<T> = (object: T, row: any) => boolean; export const isListEqualToRows = <T>(objects: T[], rows: any[], has ...

Enable the validation of properties that are not explicitly defined when using the @ValidateNested

I am using NesteJs and I am looking for a way to instruct @ValidateNested to skip properties that are not defined in the class without triggering an error: property should not exists Here are my classes: export default class InitialConfigClass extends Sha ...

Utilizing JQuery Definitions for File Upload in Typescript

I'm currently working with TypeScript and facing an issue with a file upload form. However, when I try to access the files from the input element in my TypeScript code, an error is generated. $('body').on('change', '#upload_b ...

Encountered an error while trying to load config.ts file because of an issue

Trying to set up a new protractor project to conduct tests on an angular site. Node.js, typescript, protractor, and jasmine are all installed globally. After running webdriver-manager update and webdriver-manager start in the project folder, I proceed to b ...

Is there a way to implement retry functionality with a delay in RxJs without resorting to the outdated retryWhen method?

I'd like to implement a retry mechanism for an observable chain with a delay of 2 seconds. While researching, I found some solutions using retryWhen. However, it appears that retryWhen is deprecated and I prefer not to use it. The retry with delay s ...

Creating and Injecting Singleton in Angular 2

I have a custom alert directive set up in my Angular app: import { Component } from 'angular2/core'; import { CORE_DIRECTIVES } from 'angular2/common'; import { Alert } from 'ng2-bootstrap/ng2-bootstrap'; @Component({ sele ...

Union template literal types are preprended in Typescript

Is there a method to generate specific string types from existing string types with a designated prefix? It's better to acknowledge that it doesn't exist than to dwell on this concept. type UserField = "id" | "name"; type Post ...

Launching a new tab with a specific URL using React

I'm attempting to create a function that opens a new tab with the URL stored in item.url. The issue is, the item.url property is provided by the client, not by me. Therefore, I can't guarantee whether it begins with https:// or http://. For insta ...

The TypeScript compiler does not transpile the .at() function

While converting TypeScript to JavaScript compatible with NodeJS v14 using the provided configuration: { "compilerOptions": { "lib": ["es2020"], "rootDir": "src", "outDir": "bui ...

Guide to automatically closing the calendar once a date has been chosen using owl-date-time

Utilizing Angular Date Time Picker to invoke owl-date-time has been functioning flawlessly. However, one issue I have encountered is that the calendar does not automatically close after selecting a date. Instead, I am required to click outside of the cal ...

Different return types of a function in Typescript when the parameter is either undefined or its type is explicitly asserted vary

Addressing Complexity This code may seem simple, but the use case it serves is quite complex: type CustomFunction = <B extends ['A']>( param?: B ) => B extends undefined ? 'TYPE_1' : 'TYPE_2' // Usage examples: co ...

Using both Typescript and Javascript, half of the Angular2 application is built

My current project is a large JavaScript application with the majority of code written in vanilla JavaScript for a specific platform at my workplace. I am looking to convert this into a web application that can be accessed through a browser. I believe thi ...