unconventional TypeScript interface/class properties

Currently, I am involved in a project called JSON-Schema-faker, where we utilize the TypeScript interface shown below:

interface IGeneratorSchema {
  faker?: any;
  chance?: any;
}
to define objects like: { "faker": "name.findName" } or:

{
  "chance": {
     "bool": {
       "likelihood": 100
     }
   }
}

Our next task involves incorporating support for new fields x-faker and x-chance, which essentially serve the same purpose as faker and chance. For example:


{
  "x-faker": "name.findName"
}
or:

{
  "x-chance": {
     "bool": {
       "likelihood": 100
     }
   }
}

I understand that I cannot simply add x-faker or x-chance directly to the TypeScript interface. So, how can I work around this limitation? My goal is to narrow down the accepted fields in TypeScript to only include: faker, chance, x-faker, and x-chance.

Answer №1

I am looking to enforce strict typing in TypeScript for only four specific fields: faker, chance, x-faker, and x-chance

Here is how you can declare string properties:

interface IGeneratorSchema {
    faker?: any;
    chance?: any;
    "x-faker"?: any;
    "x-chance"?: any;
}

const foo:IGeneratorSchema = { "x-faker": {} } // This is allowed
const bar:IGeneratorSchema = { bad: {} } // Error: unknown property

Important Note

The prevention of extra members is only applicable to fresh object literal scenarios : https://basarat.gitbooks.io/typescript/content/docs/types/freshness.html

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

Python's shared variables in classes lead to surprising results

After reading about Shared Variables in Python Class, I ran the following code expecting an output of: 123 123 200 200 300 300 But what I got was: 123 123 200 123 200 300 The code used was: class A: abc = 123 def __init__(self, a,b,c): ...

A step-by-step guide on adding data to a nested dictionary by using values from an already existing

In my possession is a dictionary structured similarly to JSON. Here is an example:- dito1 ={'result2':[{'math':20,'science':22,'english':31},{'math':26,'science':27,'english':33}, ...

Encountering a JSON parsing issue is causing the app to abruptly

Every time I try to open this app, it force closes and gives me an error message. I'm parsing data from my local host but I can't figure out what the error is. I'm new to Android and I'm having trouble reading the logcat. Can anyone hel ...

Using a .get() request to perform a nested fetch operation and return the fetched

I'm having trouble making this fetch request work inside the .get() request. It works fine on its own, as the console.log that shows 'first player' displays the data I need. However, when I try to call this function inside the router.get(), ...

Why does JSON.parse obscure objects in response body when using Node.js?

Whenever I utilize JSON.parse and output some fetched information with the require module, nested objects are shown as [Object]. For example, consider the following code (currently using Node version 10.15): const request = require("request"); const ur ...

Issues persist with cookies not being stored on Chrome/Edge browsers, including when interacting with localhost

I am attempting to store cookies and then retrieve them on the next page. When I add items to my "Cart" and check the logs, it seems like they are not being logged to the console or set properly. This issue is occurring in JavaScript with the server runnin ...

String validation using regular expressions

Below is the code I am using to validate a string using regular expressions (RegEx): if(!this.validate(this.form.get('Id').value)) { this.showErrorStatus('Enter valid ID'); return; } validate(id) { var patt = new RegExp("^[a-zA- ...

Best practices for making API calls with axios in React

When accessing a backend API to retrieve a product in my frontend React application using async/await axios, I have defined a function like this: export const getProduct = ():Promise<Product> => { const {data} = await axios.get<Product>(&a ...

Retrieve the JSON parameter

I'm having trouble retrieving the message part of this json-string. The code below should work, but it's not. echo $fb_response['data'][0]['message']; [VGardena] => stdClass Object ( [data] => Array ...

The application encountered an issue: Unable to find a suitable converter for the returned value, which is of the class org.json.JSONObject

I have been working on developing a REST API using the Spring framework. One of the functionalities in my API is to call another API, such as Oracle ORDS. private String processBackground(String object, String url, HttpMethod template) { HttpHead ...

Ways to eliminate a targeted key within a JSON reply

I'm working with a JSON response in postman and need to figure out how to remove a specific key from the data. In this case, I want to remove head_out_timestam - no matter where it is in the object tree. This needs to be done using javascript. Any he ...

Here are the steps to fix the error "SyntaxError: Cannot use import statement outside a module" when running a Jest test case

As a newcomer to the world of reactjs development, I am currently working on creating a code editor using the monaco-editor library within my React TypeScript project. The integration of the monaco editor along with the web worker has been successfully com ...

Firebase is storing object values as 'undefined'

My goal is to retrieve user details from my firebase database while using Ionic and Typescript. Here is how I add a user: addToDatabase(user: User) { let isInstructor = user.isInstructor == null ? false : user.isInstructor; this.afDB.list("/users/").push ...

Ways to toggle checkboxes to show or hide their child items and subitems

I'm working on creating a straightforward menu that allows users to click on a parent checkbox to expand or collapse its children. The challenge I'm facing is how to make the parent checkboxes expand while hiding the children items within them wh ...

What is the proper way to specify the type for the `clean-element` higher-order-component in React?

Error message: 'typeof TextareaAutosize' argument cannot be assigned to a type 'Component<{}, {}, any>'. Error: Property 'setState' is not found in 'typeof TextareaAutosize'. Here is the code snippet causin ...

Encountering an "unexpected end of stream" error on Android while streaming JSON data

I am encountering an issue with a piece of code that involves making a call to a server to retrieve and parse a large JSON file using Jackson JSON Parser. Although the code is functioning properly, I occasionally receive an IOException stating "unexpecte ...

Guide on connecting a Kendo ComboBox to an Observable instance

I'm currently facing an issue with integrating a DropDownList with an Observable class. Below is the code snippet for the observable class: var viewModel = kendo.observable({ dsMember: new kendo.data.DataSource({ // dataS ...

Setting a default check on a checkbox within an ngFor loop in Angular 2

I'm attempting to initialize a default value as checked for a checkbox within my ngFor loop. Here is an array of checkbox items I am working with: tags = [{ name: 'Empathetic', checked: false }, { name: 'Smart money', che ...

Working with JSON_EXTRACT in MySQL 5.7 when dealing with identical key names within a JSON array

I am working with a JSON object that is stored in MySQL. Here is an example of the JSON data: [ { "key": "user_agent", "value": "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media C ...

Spring MVC: Issue with POST request and JSON object containing an array resulting in a bad request

Trying to fetch parameters from an http POST request using Spring MVC. The POST request contains the following JSON object (content-type : application/json) with an array of customObjects: { "globalId":"338", "lines":[ { "id": ...