Can you explain the concept of being "well-typed" in TypeScript?

The website linked below discusses the compatibility of TypeScript 2.9 with well-defined JSON.

What exactly does "well-typed" JSON mean? As far as I understand, JSON supports 6 valid data types: string, number, object, array, boolean, and null. Therefore, every JSON data type should align well with TypeScript basic types. This is why the concept of being "well-typed" is confusing to me.

In contrast, what would be an example of "not-well-typed" JSON?

Answer №1

The concept is best illustrated by this example:

// ./src/settings.json
{
    "dry": false,
    "debug": false
}

// ./src/foo.ts
import settings from "./settings.json";

settings.debug === true;  // This works fine
settings.dry === 2;       // Error! You cannot compare a boolean with a number

One may assume that comparing settings.dry === 2 in JSON would not lead to any compilation errors, but it will actually fail at runtime.

TypeScript infers the types from the JSON properties and detects mismatches such as comparing a boolean to a number, which helps prevent logical errors during development.

This can be compared to using TypeScript like this:

const settings = {
    dry: false,
    debug: false
}

if (settings.dry === 2) { ... }

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 JSON API filtering within a Next.js application

Recently delving into the world of coding, I've embarked on a personal project that has presented me with a bit of a challenge regarding API filtering. My goal is to render data only if it contains a specific word, like "known_for_department==Directin ...

maintaining accountability in package.json

Adding commas to the last element of an object or array in package.json can impact how blame is preserved. For example, if we start with this code in commit A: { "version": "0.0.1" } Then in commit B, another field is added: { "version": "0.0.1", ...

Error: Can't access the 'http' property because it's undefined in Angular 2

Recently, I successfully integrated the gapi client into my Angular 2 application. However, I am now facing an issue where my http object is showing as undefined and I can't seem to figure out why. Here's the snippet of code that's causing ...

Higher order components enhance generic components

I'm facing an issue where I want to assign a generic type to my React component props, but the type information gets lost when I wrap it in a higher order component (material-ui). How can I ensure that the required information is passed along? type P ...

The not-null constraint is violated in the "id" column because of a null value when using Sequelize Typescript

My Database Setup Journey Recently, I embarked on a database adventure where I decided to use Sequelize-Typescript to assist me with all the heavy lifting in terms of database operations. The first step was creating a table called uma_tbl_users, and here ...

choose based on attributes within sub-array

I'm currently working on automating the process of updating AWS Lambda layers and the associated functions. To identify the functions using a specific layer, I am parsing the JSON output from the AWS CLI when listing all the functions in my AWS accoun ...

Navigating nested data structures in reactive forms

When performing a POST request, we often create something similar to: const userData = this.userForm.value; Imagine you have the following template: <input type="text" id="userName" formControlName="userName"> <input type="email" id="userEmail" ...

Oops! The program encountered an issue where it couldn't access the "Point" property because it was undefined. This occurred while working with openlayers 3 and jsts on

I am currently working on implementing a buffer function for some features that have been drawn on a map following this particular example. However, I am encountering the following error: ERROR TypeError: Cannot read property 'Point' of undefin ...

Providing the correct context to the function in Angular's dialog data is crucial for seamless

Currently, I have a scenario where a service and a component are involved. In the service, there is an attempt to open a dialog in which a reference to a method existing in the service is passed. The code snippet below provides an example: export class So ...

Is there a way to specify a type for a CSS color in TypeScript?

Consider this code snippet: type Color = string; interface Props { color: Color; text: string; } function Badge(props: Props) { return `<div style="color:${props.color}">${props.text}</div>`; } var badge = Badge({ color: &ap ...

Ionic 2: Unveiling the Flipclock Component

Can anyone provide guidance on integrating the Flipclock 24-hours feature into my Ionic 2 application? I'm unsure about the compatibility of the JavaScript library with Ionic 2 in typescript. I have searched for information on using Flipclock in Ionic ...

Displaying related data in jqGrid using foreign keys

My jqGrid is connected to a JSON datasource provided by a WCF web service. The WCF method retrieves a list of ids showing the relationship between a user, branch, and role. For instance, a user can have different roles in different branches. [{"entityHash ...

What could be causing my code to not run after subscribing to the observables?

In my code, I have two methods that return two lists: one for accepted users and the other for favorite users. The first part of my code works well and returns both lists, but in the second part, I need to filter out the accepted users who are also on the ...

What causes the Access-Control-Allow-Origin error to appear with AJAX requests but not with Rails?

After attempting to retrieve a response from the API of Career Builder using AJAX (trying xml, json, and jsonp), I consistently encountered the "Access-Control-Allow-Origin" error. However, when I followed icodeya's tutorial and retrieved a response f ...

Vue 3 Single Page Application. When selecting, it emits the language and the contentStore does not update the content exclusively on mobile devices

My Vue 3 Single Page Application is built on Vite 4.2 and TypeScript 5.02. When I click to select a language, it emits lang.value and in the parent component App.vue, contentStore should update the content. It works flawlessly on my Linux Ubuntu desktop i ...

Turn off the touch events system for Ionic 2 on the leaflet map's draw controller

Seeking guidance on how to disable data-tap functionality in Ionic 2 within a leaflet map div. Anyone familiar with this? In Ionic-v1, the solution involved adding data-tap-disabled="true" to the map container (ion-content). I recently integrated the lea ...

Cypress encountered an error: Module '../../webpack.config.js' could not be located

Every time I attempt to run cypress, an error pops up once the window launches stating "Error: Cannot find module '../../webpack.config.js'" Within my plugins>index.js file, I have the following in module.exports webpackOptions: require('.. ...

Transform JSON data into an array using the nlohmann/json library

It's been more than two decades since I last delved into C++, so my skills are a bit rusty in this area. Currently, I am utilizing the nlohmann/json json.h library and facing the challenge of converting a JSON string that represents an array of objec ...

Is it possible to use the `fill` method to assign a value of type 'number' to a variable of type 'never'?

interface Itype { type: number; name?: string; } function makeEqualArrays(arr1: Itype[], arr2: Itype[]): void { arr2 = arr2.concat([].fill({ type: 2 }, len1 - len2)); } What is the reason for not being able to fill an array with an ob ...

Unable to post form data into database due to Javascript undefined data situation

I've been working on an HTML form that can interact with a PHP API to retrieve client data and then update user stats in a MySQL database. Currently, I am converting the data into a JSON object and using JSON.stringify to create a string for sending ...