Does the Typescript interface align with the specifications of this object?

I'm looking to define a TypeScript Interface for objects similar to these:

{
  "id": 34728,
  "url": "https://example.com/image.jpg",
  "commonNames": {
    "de": ["Apfel", "Kulturapfel"],
    "en": ["apple"],
    "th": ["แอปเปิล"]
  },
}

Am I on the right track with my method? I have some doubts, especially regarding the commonNames property.

interface Food {
  id: number;
  url: string;
  commonNames: {
    [index: string]: string[];
  };
}

Answer №1

It has been confirmed in @Nicholas Tower's comment that your approach is correct.

There is a suggestion for a small improvement: instead of having three strings in your type definition, each representing different things, consider creating type aliases for better clarity:

type Uri      = string;
type Language = string;
type Name     = string;

interface Food {
  id: number;
  url: Uri;
  commonNames: {
    [index: Language]: Name[];
  };
}

These aliases do not change the typing but enhance understanding of the attributes.

Additionally, using type aliases allows for attaching TSDoc comments for documentation purposes:

/**
/ * A globally unique, monotonically increasing identifier for a dictionary entry
**/
type Id         = number;

/**
/ * A URI
**/
type Uri        = string;

/**
/ * A URI referencing a picture of the food
**/
type PictureUri = Uri;

/**
/ * An ISO 639-1:2002 Alpha-2 Language Code
**/
type Language   = string;

/**
/ * The name of the food
**/
type Name       = string;

interface Food {
  id: Id;
  url: PictureUri;
  commonNames: {
    [index: Language]: Name[];
  };
}

This example highlights the benefit of using type aliases for documentation.

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

Node is experiencing difficulty incorporating the AWS DynamoDB package into the project

Important Note: Although AWS SAM and DynamoDB are mentioned here, this question is primarily related to the AWS JavaScript SDK, or potentially just a Node/NPM query at its core. It should be answerable by anyone experienced in developing Node/JavaScript ap ...

Create a JSON file with UTF-8 encoding

I'm currently developing a function that writes JSON data to a file, and everything seems to be working well. However, despite specifying the output as UTF-8, Oxygen is having trouble reading pound and euro signs. Here's the Java code snippet: ...

Encounter a Config validation error while trying to utilize Nest.js ConfigService within e2e tests

I'm encountering an error despite having the NODE_ENV=development variable in my .env file. The error message reads: ● Test suite failed to run Config validation error: "NODE_ENV" must be one of [development, production] 11 | imports ...

Troubleshooting: Authentication guard not functioning properly in Angular 2 due to HTTP request

As I work on implementing a guard for certain routes in my application, I face an issue. To grant access to the route, my intention is to send an HTTP request to my express backend API and check if the user's session exists. I have explored various e ...

What is the reason behind create-next-app generating .tsx files instead of .js files?

Whenever I include with-tailwindcss at the end of the command line, it appears to cause an issue. Is there any solution for this? npx create-next-app -e with-tailwindcss project_name ...

Trouble accessing nested components in Angular CLI beyond the first level of components

I'm diving into Angular CLI for the first time and trying to recreate a previous web project of mine. I've managed to nest and display components inside the root component successfully, but after that, I'm facing issues referencing any compo ...

Halt of dispatcher playback occurs after a duration of 10 minutes with discord.js

Currently, I've been working on a music bot using discord.js. To handle audio streaming, I'm utilizing @discordjs/opus and ytdl-core-discord. Everything runs smoothly when testing the bot locally on my machine - songs from YouTube are played with ...

Encountered a glitch while trying to test the application on an Android device following the connection to Android Studio

After following the steps outlined in the tutorial on connecting to wifi, I successfully linked my phone to my desktop wirelessly through the router. However, while I can test most applications wirelessly, I am encountering issues with those that require J ...

The Application Insights Javascript trackException function is giving an error message that states: "Method Failed: 'Unknown'"

I've been testing out AppInsights and implementing the code below: (Encountering a 500 error on fetch) private callMethod(): void { this._callMethodInternal(); } private async _callMethodInternal(): Promise<void> { try { await fetch("h ...

TS2304: The build process is unable to locate the name 'iterable' within @types

As an experienced dog attempting to master new tricks like npm and TypeScript, I find myself faced with a challenge in my Visual Studio 2017 project. Despite setting it to "Latest" TypeScript 2.5 and adding @types/jquery (3.2.12), the project keeps throwin ...

Instead of being viewed in the browser, the CSV file is being downloaded

I'm currently using Jhipster and have a function generated by Jhipster to open files in the browser. However, I'm facing an issue with this function when it comes to opening CSV files - instead of opening in the browser, they are being downloaded ...

attempting to refine an array of objects using another array within it

I am currently filtering a group of objects in the following manner: [ { "Username":"00d9a7f4-0f0b-448b-91fc-fa5aef314d06", "Attributes":[ { "Name":"custom:organization", "Valu ...

typescript encounters issues with union type while trying to access object properties

I'm puzzled by the errors I'm encountering in my IDE with the following code: I defined some interfaces/types interfaces/types: interface GradientColor { type: string; value: { angle: string | number; colours: string[]; }; } inte ...

Differences between Typescript and Node versions

Is there a connection between the version of Typescript and the version of Node since Typescript is a global npm module? In other words, is there a minimum Node version required to run a specific version of Typescript. ...

Working with arrays in Angular 4 to include new items

I am struggling with the code below: export class FormComponent implements OnInit { name: string; empoloyeeID : number; empList: Array<{name: string, empoloyeeID: number}> = []; constructor() { } ngOnInit() { } onEmpCreate(){ conso ...

Using TypeORM: Implementing a @JoinTable with three columns

Seeking assistance with TypeORM and the @JoinTable and @RelationId Decorators. Any help answering my question, providing a hint, or ideally solving my issue would be greatly appreciated. I am utilizing NestJS with TypeORM to create a private API for shari ...

Dynamic TypeScript class constructor argument typing determined by user input

I am working on creating a dynamic class that can adapt its argument properties based on a certain value. To illustrate this concept, let's consider a simple example: Imagine I have a class called Customizer, and depending on the value of the mode pr ...

The absence of a 'body' argument in the send() json() method within the Next.js API, coupled with TypeScript, raises an important argument

Currently, I have set up an API route within Next.js. Within the 'api' directory, my 'file.tsx' consists of the following code: import type { NextApiRequest, NextApiResponse } from "next"; const someFunction = (req: NextApiReq ...

Conditional validation in Typescript based on the nullability of a field

I have come across the following code snippet: type DomainFieldDefinition<T> = { required?: boolean } type DomainDefinition<F, M> = { fields?: { [K in keyof F]: DomainFieldDefinition<F[K]> }, methods?: { [K in keyof M]: M[K] & ...