Objects within objects in TypeScript

Looking to nest JavaScript objects in TypeScript? Here's how:

let endpoints = {
    auth: {
        login: "http://localhost:8079/auth/login"
    }
};

If you try the following code, it won't work as expected:

private endpoints: Object = {
    auth: {
        login: "http://localhost:8079/auth/login"
    }
};

You might encounter an error like this:

error TS2339: Property 'auth' does not exist on type 'Object'.

Answer №1

Utilizing interfaces in TypeScript can help organize your code:

interface EndpointAuth {
    login: string;
}

interface Endpoint {
    auth: EndpointAuth;
}

let endpoints: Endpoint = {
    auth: {
        login: "http://localhost:8079/auth/login"
    }
};

(View code in playground)

You can also define types with the same structure as interfaces:

type EndpointAuth = {
    login: string;
}

type Endpoint = {
    auth: EndpointAuth;
}

(View code in playground)

Alternatively, you can use inline type declarations for objects:

let endpoints: { auth: { login: string } } = {
    auth: {
        login: "http://localhost:8079/auth/login"
    }
};

You are not limited to just one approach and can combine them as needed.


Edit

Explanation on why using Object may not work as intended:

Assigning a variable the type of Object might not be the ideal choice, consider using any instead:

var endpoints2: any = {
    auth: {
        login: "http://localhost:8079/auth/login"
    }
};

Specifying a type as Object is similar to defining an empty object ({}) which may not align with your intentions. Using any sacrifices some type safety but allows for more flexibility:

let o: any = { x: 3, y: 6 };
console.log(o.z.toString());

Using any will not catch errors at compile time but may result in runtime errors. It's recommended to define specific types for better error checking:

let o: { x: number, y: number } = { x: 3, y: 6 };
console.log(o.z.toString());

Answer №2

One way to structure your code is by declaring an Interface.

In this specific scenario

interface IEndpoints
{
 auth: {
  login: string;
 }
}
private endpoints: IEndpoints = {
  auth: {
    login: "http://localhost:8079/auth/login"
  }
};

Answer №3

It's possible that the version of TypeScript you were previously using did not support this feature, but in the current version it is indeed supported.

interface APIEndpoints {
  [path: string]: APIEndpoints | string
}

const apiEndpoints: APIEndpoints = {
    users: {
        profile: "http://api.example.com/users/profile"
    }
}

Answer №4

To ensure type safety, it is recommended to create a custom class or interface:

interface ICustomInterface
{
    authentication: IAuthentication;
}

interface IAuthentication
{
    loginUrl: string;
}

private apiEndpoints: ICustomInterface = {
    authentication: {
        loginUrl: "http://localhost:8079/auth/login"
    }
};

The error you are encountering is due to declaring endpoints as type Object, which does not have an 'authentication' property.

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

Error in NW.js file pattern: The package.json file was not found within the source directory file glob patterns

When trying to run a NW.js script located in the /tool/nw.js folder with a source folder set to /dist, an error related to the glob pattern not finding the srcDir (/dist) is thrown. While using glob:false in the configuration resolves the issue, I am curio ...

Tips for downloading an XLSX file

I have a file in the assets directory that I would like to be able to download for my project. <button className='p-2 bg-green-600 my-3 text-white '> <href='../../../Assets/file/form_upload_lead.xlsx'>Download Format Upl ...

Javascript - Single line conditional statement

As I continue to improve my JavaScript skills, I'm looking for guidance on optimizing the following if statement. Is there a way to shorten it, possibly even condense it into one line? How can I achieve that? onSelect: function (sortOption) { th ...

typescript exploring the versatility of dynamic types and generics

Understanding TypeScript dynamic and generic types can be challenging for me. The goal is to create a function that generates an object with a specific type, where some properties of the object must match the parameters provided to the function. Essentia ...

Assign the textbox's value to be the earliest selected date from the datepicker

Can anyone assist me? I have a working code that activates only the specific day of the week I want on the datepicker. However, the textbox doesn't have a default value and I would like it to display the first date activated in the datepicker. In th ...

The installed version of Chromedriver is newer than the current version

Currently, I am utilizing Selenium for end-to-end tests with jest. My browser of choice is Chrome version 85.0.4183.121, and the correct chromedriver version is present in my PATH. When I execute chromeversion -v in the command line, it returns ChromeDriv ...

Angular directive ng-clickIs the directive in angular known as

I am struggling to understand why my ng-click function in my directive is not triggering the fooControls clickTest. Why isn't clickTest logging to the console? Is there a more efficient way to accomplish this? Custom Directive app.directive('fo ...

Potential Scope Problem in Angular JS Controller

The HTML code snippet I have is as follows: <body ng-controller = "Control as control"> <button ng-click = "control.prepareAction()">Do Action </button> <div id="one" ng-hide = "!control.showOne" > <div> <h6> ...

What causes alterations in a single cell to spread to adjacent cells within this 2D array initialized using the fill function?

I seem to be encountering an issue with this 2-dimensional array in JavaScript. It appears that when I modify a[1][0], the value of a[0][0] also changes. Could it be a problem with how I am initializing it? If so, what is the correct way to initialize it ...

Encountered an error while attempting to compare 'true' within the ngDoCheck() function in Angular2

Getting Started Greetings! I am a novice in the world of Angular2, Typescript, and StackOverflow.com. I am facing an issue that I hope you can assist me with. I have successfully created a collapse animation for a button using ngOnChanges() when the butto ...

Detecting changes in input elements when setting values in AngularJS

Access Code: http://jsfiddle.net/mb98y/309/ HTML <div ng-app="myDirective" ng-controller="x"> <input id="angular" type="text" ng-model="data.test" my-directive> </div> <button onclick="document.querySelector('#angular&a ...

User Interface Components in Backbone Views

I'm considering if there is a more efficient approach to this situation. I've got some HTML that requires event handling. Query 1: Since there are no data, models, or collections associated with it, do I need a render method? Query 2: I believ ...

Swapping out meshes on the fly using three.js動态替换单个网格与

I have a unique idea for a breakout game where the paddle is shaped like a piece of roof trim, with its shape changing based on the pitch of the roof. Hitting special bricks will alter the pitch variable, thus changing the "steepness" of the paddle. Howeve ...

What are the steps to remove text within a list item using jQuery or regular JavaScript in a WordPress theme?

I need to remove the word "previous" from an li element in a wordpress theme. the text to delete <ul class="flex-direction-nav"> <li class="flex-nav-prev"> <a class="flex-prev" href="#">Previous ...

I'm having trouble getting the data to parse correctly in ajax. Can anyone explain why it's not working?

I have implemented a system where an excel file is uploaded using AJAX, and information about the success or failure of the upload is sent from the upload page to the PHP page using json_encode. However, I am facing an issue with accessing this data indivi ...

Making an Ajax call that doesn't block and figuring out how other JavaScript can wait for the object to populate

Our project requires an asynchronous AJAX call with the parameter set to true instead of false in order to avoid blocking other JavaScript functions. However, we also have some JavaScript files that depend on the success object returned by the AJAX call. W ...

What is the best way to combine the elements of two arrays within a v-for loop?

Within my code, I have defined two arrays: users and projects. Each array contains unique numbers as IDs. A project can be owned by multiple users, so in the projects array, there is an array of user IDs named ownersId that corresponds to the id of users i ...

Ways to transfer large amounts of data to Amazon Web Services

After reading the node documentation on sqs.sendMessage, I noticed that it mentions the ability to send messages up to 256KB in size. However, my messages tend to exceed this limit. What is the recommended approach for handling large payloads in this scena ...

Verifying that objects are eligible for garbage collection

My program in node.js receives a high volume of messages. Each time a message is received, I create a new object and pass the message content to it. Inside the constructor of the new object, various operations are performed, including some mongo tasks with ...

Opening a browser tab discreetly and extracting valuable data from it

Greetings to the experts in Chrome Extension development, I am exploring ways to access information from a webpage without actually opening it in a separate tab. Is there a method to achieve this? Here's the scenario: While browsing Site A, I come a ...