Accessing properties using bracket notation in Typescript is a powerful feature that

I wish to retrieve a typed object using bracket notation like this:

interface IFoo {
    bar: string[];
}

var obj: IFoo = { bar: ["a", "b"] }
var name = "bar";
obj[name]. // type information lost after dot 

As per the specification 4.10, it seems to be the expected behavior:

A bracket notation property access of the form ObjExpr [ IndexExpr ]  
....  
Otherwise, if IndexExpr is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any.

Could someone confirm if this is accurate and suggest any workarounds.

Edit: My situation involves object minification as shown below:

var props = {long_name: "n"};    
var shortName = props.long_name;

function(minObj) {
    var value = minObj[shortName]
    var newMinObj = {};
    newMinObj[shortName] = value.toUpperCase();
    db.save(newMinObj)
}

Answer №1

For the sake of maintaining the original interface, I decided to include it separately.

export interface IIndexable {
  [key: string]: any;
}

I then make reference to it whenever necessary.

getEditDate(r: IRestriction, fieldName: string) {
    ...
    value={(r as IIndexable)[fieldName] as Date}

The method works effectively. If I discover a way to streamline it further, I will provide updates.

Answer №2

Instead of utilizing a variable within the obj[x] parameter, you have the option to directly write it out by accessing this syntax:

obj["bar"].sort

The necessity for using a variable in this context arises when selecting an arbitrary property from your IFoo interface. However, if you only have one string array defined within IFoo, then this step becomes redundant. In cases where multiple string arrays are present in your IFoo, you can make use of indexing and implement the following:

interface IFoo {
    bar: string[];
    bar2: string[];
    [key: string]: string[]; // Enabling index feature on IFoo without introducing new property
}

With this setup, you could execute commands like:

var name = "bar";
obj[name].sort;

This approach also grants you flexibility to add new properties and perform operations such as:

obj["some new property"] = ["a", "b"];
obj["some new property"].sort;

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

The assignment of Type Program[] to a string[] is not valid

I am working with a class that contains information about different programs. My goal is to filter out the active and inactive programs, and then retrieve the names of those programs as an array of strings. Below is the structure of the Program class: ex ...

Assessing the invalidity of user-defined type guards within class implementations

I just wrote this Typescript code and tested it in a sandbox. Check out the code snippet below: class Foo { public get test() : string|number{ return "foo" } public hasString() : this is { test:string }{ return type ...

Testing Angular components using mock HTML Document functionality is an important step in

Looking for help on testing a method in my component.ts. Here's the method: print(i) { (document.getElementById("iframe0) as any).contentWindow.print(); } I'm unsure how to mock an HTML document with an iframe in order to test this meth ...

Leveraging Angular Firebase MatTable with the power of 2 observables in 1

I'm currently facing an issue with my Firebase database data structure where I have a reference to a user id. Here's an example of the original data in my collection: { city: new york, country: usa addedBy: feibf78UYV3e43 // This is the USER ID ...

Combining indexed types with template literals -- add a prefix to each key

Start with type A and transform it into type B by adding the prefix x to each key using Typescript's newest Template Literal Types feature: type A = { a: string; b: string; }; // Automatically generate this. type Prefixed = { xa: string; xb: ...

How can I take photos in bulk when I open the camera on Ionic 3?

Is there a way to capture multiple images at once using the camera? Currently, I am only able to capture one image when the user clicks. However, I would like to capture four images when the user clicks the success button. let options: CaptureImageOption ...

Transform Material UI Typography to css-in-js with styled-components

Can Material UI elements be converted to styled-components? <Container component="main" maxWidth="XS"> <Typography component="h1" variant="h5"> Sign in </Typography> I attempted this for typography but noticed that t ...

Learn how to extend components in Typescript and determine necessary arguments. Discover how to apply this knowledge in an Angular use case by extending mat-side-nav

Background: The Angular Material Design component known as mat-side-nav operates in a specific structure for its dynamics: <mat-sidenav-container> <mat-sidenav> </mat-sidenav> <mat-sidenav-content> </mat-sidenav-conten ...

angular component that takes a parameter with a function

Is there a way for my angular2 component to accept a function as a parameter? Uncaught Error: Template parse errors: Can't bind to 'click' since it isn't a known property of 'input'. (" minlength="{{minlength}}" [ERROR -&g ...

The TS-Mocha and Chai duo have encountered a hitch: a peculiar error message, TS2695, informing them that the left side of the

Software Versions: "ts-mocha": "^8.0.0", "ts-node": "^10.3.0", "chai": "^4.3.4", Sample Code: expect(wrapper.find(MyListItem)).to.have.length(3); Execution Command: ts-mocha tests/**/*.tsx -r u ...

"Experiencing issues retrieving user-modified values in NativeScript's TimePicker component

I'm having trouble retrieving the user-modified value from a TimePicker. Instead of getting the modified value, I keep receiving the original value that was initially set in the control. Below is my component template: <TabView [(ngModel)]="tabSe ...

Issue with Material Sort functionality when null objects are present

I've encountered an issue with my code. I created a feature that adds empty rows if there are less than 5 rows, but now the sort function is no longer functioning properly. Strangely, when I remove the for loop responsible for adding empty rows, the s ...

Exploring the integration of the mongodb-stitch library within an Angular 4 application

I have been experimenting with the MongoDB Stitch service in Angular, and so far I have successfully implemented the service. However, the only way I have managed to connect to the service is by adding the js library hosted on AWS directly into the html pa ...

Add the onclick() functionality to a personalized Angular 4 directive

I'm facing an issue with accessing the style of a button in my directive. I want to add a margin-left property to the button using an onclick() function in the directive. However, it doesn't seem to be working. Strangely, setting the CSS from the ...

Tips for retrieving the most recent number dynamically in a separate component without needing to refresh the page

Utilizing both the Helloworld and New components, we aim to store a value in localStorage using the former and display it using the latter. Despite attempts to retrieve this data via computed properties, the need for manual refreshing persists. To explore ...

What is the best way to selectively pass certain values to the args object?

Is there a way in TypeScript to pass only one argument into args and have other values be default without using "args = {}" or declaring defaults within the function to avoid issues with intellisense? function generateBrickPattern ( wallWidth: number, ...

The @ViewChild in Angular 2 seems to be unable to detect the BaseChartDirective from the ng2-charts

I'm currently using ng2-charts v1.5.0 and I'm facing an issue with updating the chart data after a click event. Despite following suggestions from other sources, I am unable to get it to work properly. Here is a snippet of my code: <div styl ...

Incorporating Moralis into Ionic Angular with TypeScript

I'm currently developing an app using Ionic Angular (TypeScript) that will be compatible with both Android and iOS devices. I've decided to incorporate the Moralis SDK to establish a connection with the Metamask wallet. Here's a summary of ...

Angular - passing information to a nested component

Within my application, I have a main component along with three sub-components. I am passing data to these three sub-components and using setTimeout to manage the timing of the data being sent. The first sub-component displays for 5000 milliseconds. The ...

Ways to eliminate the white background gap between pages on ionic

While developing an app using Ionic, I encountered a strange issue. Everything runs smoothly on a browser, but when testing the app on an Android 5 device, I noticed a white background appearing between pages. The app loads correctly with the custom splas ...