Is it possible to confirm in Typescript if a given string key is valid for a specific type?

Apologies for the unclear wording of the question.

Imagine having a data structure like this:

type ExampleObject = {
  arr: Array<{x: number, y: Array<{z: string}>}>;
  obj: {[key: string]: number};
}

I want to ensure that paths are valid - preferably at compile time, but runtime validation would also suffice. Here's an example of what I have in mind:

function setValue<T>(object: T, path: string, value: unknown) {
  // perform the set operation
}

The goal is for the following to be achievable:

const o: ExampleObject = { arr: [], obj: {} };
setValue<ExampleObject>(o, "arr[0].x", 1);
setValue<ExampleObject>(o, "arr[0].y[2].z", "hello world");
setValue<ExampleObject>(o, "obj['x']", 1);

If you were to attempt something like this, it should fail, since there is no ExampleObject.a:

setValue<ExampleObject>(o, "a", 1);

An ideal implementation would provide Intellisense and IDE error detection for developers, but a runtime resolution would suffice as well.

Answer №1

Typescript does not support checking properties that are in string format.

If you have configured your TestObject in a specific way, it may give an error when attempting to access properties using string indexes due to the lack of an index type defined.

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

forEach was unable to determine the appropriate data types

define function a(param: number): number; define function b(param: string): string; define function c(param: boolean): boolean; type GeneralHooks<H extends (...args: any[]) => any> = [H, Parameters<H>] const obj = { a: [a, [1]] as Gene ...

Injection of environmental variables into app services

Through the use of Nx, I have created multiple apps that each have their own environment with different API URLs. The Nx Workspace library includes shared services that are utilized among all apps, however, it is necessary to pass the environment-api-url w ...

Setting up ReactJS and TypeScript in a fresh MVC5 project from scratch

After extensively trying out various tutorials, I have yet to successfully run a basic MVC5 project using TypeScript and ReactJS. For reference, I have created these projects from scratch in Visual Studio 2015 with .NET 4.6.1, using the ASP.NET Web Applic ...

Incorrect type deduction on generic array mapping

I have observed an unexpected interaction in the following scenario. When attempting to iterate using the map function with the generic options, I noticed that the item inside is not of the expected type. const foo = <T extends string[]>(options: T, ...

Unexpected outcome when returning a map

Encountered a puzzling issue that requires immediate clarification. When I input the following code into my project: this.metadata = json.metadata.map((x) => {return new Metadatum(x);}); console.log(this.metadata[0].value); The output consistently sho ...

The Nestje subscription is encountering a NULL value and displaying an error message stating: "Non-nullable field Subscription cannot be returned as null."

I attempted to implement a Subscription in my nestjs project with GraphQL, but encountered the following error message: Cannot return null for non-nullable field Subscription Below is the code snippet: //* ~~~~~~~~~~~~~~~~~~~ Subscription ~~~~~~~~~~~ ...

Error with tsc rootDir due to Docker's installation of yarn in root directory

I am encountering a problem with my node project which serves a simple "hello world" server. Everything runs smoothly when I run it locally, but when I try to run it inside Docker, a /opt/yarn-v1.21.1 folder is created which leads to a rootDir error: erro ...

Transforming dynamic class based on state value from React to TypeScript

I'm trying to implement this React function in TypeScript, but I'm encountering errors. const ListItem = ({ text }) => { let [showMore, setShowMore] = useState(false); return ( <div className="item"> ...

Unleashing the power of TypeScript with Solid JS Abstract Class

Why am I getting an undefined error for my calcUtilisation method when using an Abstract Class as the type in createStore? Is there a way to utilize a type for the data along with a method within the same class for createStore? abstract class Account { ...

Issues with the File plugin in Ionic 2

Currently, I am working on integrating Quickblox into my Ionic2 application. I have successfully implemented all the required functionalities except for file uploading. In Quickblox, there is a specific function that needs to be used for uploading files, a ...

Ways to initiate update notification when altering an array object?

I am working on my Angular4 app and I have a component that uses a *ngFor directive to iterate over an array: <div *ngFor="let person of persons"> {{person.name}} {{person.car}} </div> Within the same component, there is a feature to ...

Encountered an issue with importing a TypeScript module

One issue I encountered is that when importing a module in an app.ts script, the '.js' extension is not included in the import line of the compiled js file. In my app.ts file, I have import {ModuleA} from './ModuleA' After compilation ...

Error TS2307 - Module 'lodash' not found during build process

Latest Update I must apologize for the confusion in my previous explanation of the issue. The errors I encountered were not during the compilation of the Angular application via Gulp, but rather in the Visual Studio 'Errors List'. Fortunately, I ...

Using a Typescript Class Decorator to Enhance Functionality

Can anyone help me implement a timing decorator for my Typescript classes similar to what is commonly used with Python? Consider the following example class class MyClass() { private _foo: string = 'abc'; public printX() : void { conso ...

What is the best way to access the type of a generic property within a type?

type Mother = { action<X>(alpha: X, bravo: string):void } type ChildArguments = Parameters<Mother['action']<number>> // encountered an issue Assuming the aforementioned code is functioning properly, I will be able to execut ...

Auto-populate model objects with information automatically

I have a model... export class myModel{ PropertyA: string; PropertyB: number; PropertyC: string; PropertyD: number; } The data retrieved consists of... this.store.select(myDataStoreName) .subscribe(data=> { } This is how the ret ...

Automatic type inference in function parameters in Typescript

When attempting to infer the type of Data based on input parameters, it correctly infers when the data is an object type; however, it defaults to 'unknown' when the data is a function type. https://i.sstatic.net/wkuQa.png declare function getType ...

Adjust the tsconfig in Typescript to only output files to one specified folder, excluding the other folder from

Currently, I am in the process of converting a JavaScript project to TypeScript. My goal is to set noEmit = true for one folder while keeping noEmit = false for another folder. The reason behind this is that my client-side (Angular) code is configured thr ...

Challenges in Transitioning from Vue.js Typescript Options to Composition API

After successfully solving the issue, take a step-by-step look through the question to understand how the problems were fixed. I recently explored the composition API () and attempted to convert my TypeScript-based existing code from Vue.js Option API. Un ...

Tips for adding text to a file in a VSCode Extension

Currently working on an exciting new VSCode extension project. Seeking advice on the best way to locate a file by name and insert text into it. Omitting any code here as it's not necessary at this point ;) Feeling a bit overwhelmed by the complexity ...