Retrieving the attribute key from a dynamically typed object

Having this specific interface structure:

interface test {
   [key: string]: string
}

along with an object defined as follows:

const obj: test ={
   name: 'mda',
   telephone: '1234'
}

Attempting to utilize this object in a variable, the intellisense feature fails to function properly for this particular object. Essentially, it allows selecting a key that does not actually exist within the object.

const myName = obj.ndfnasdfn

No error is displayed by the compiler for such a key selection. You can access the playground area here: playground

An update involving a nested object: For this nested object scenario, what are the possible solutions? I implemented @Titian Cernicova-Dragomir's solution for the nested object mentioned below, however, no error is shown by the compiler.

interface test {
[key: string]: string
 }

 function createTest<T extends test>(o: T) {
     return o;
 }
 interface state {
     test1: test,
     test2:test
 }
 const state: state = {
    test1:createTest({
        t1:'m',
        t2:'e'
  }),
  test2: createTest({
    t3:'sss'
     })
  }
 const {test1, test2} = state
 const t1 = test1.sdfsafsdf //no error

playground

Further update: If we choose not to utilize the createTest function, and instead don't specify the type for the state object like demonstrated here playground

I proposed using types for the state object to prompt a compiler error for keys that do not exist in test1

Answer №1

When you explicitly specify the type of a variable, it becomes the final type and the compiler does not infer any additional information for that variable.

If you remove the annotation, the compiler will infer the type of the variable.

const obj ={
   name: 'mda',
   telephone: '1234'
}

If you want to restrict a variable to only accept string values, you can achieve this by using a function to constrain the type while still letting the compiler infer the overall type:

interface test {
    [key: string]: string
}

function createTest<T extends test>(o: T) {
    return o;
}

const obj = createTest({
    name: 'mda',
    telephone: '1234'
    // age: 10 // This will cause an error as age is not a string
});
obj.name // Ok
obj.sss // Error

Playground link

For nesting data structures, such as in the example provided, you need to create a function to generate state instead of just test. The same rule applies - when the types of test1 and test2 are explicitly defined, those types become final regardless of what createTest returns.

interface test {
    [key: string]: string
}

interface state {
    test1: test,
    test2:test
}
function createTest<T extends state>(o: T) {
    return o;
}
const state = createTest({
    test1: {
        t1: 'm',
        t2: 'e'
    },
    test2: {
        t3: 'sss'
    }
});
const {test1, test2} = state
const t1 = test1.sdfsafsdf //This will result in an error

Playground link

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

Issue with displaying tab icons in Ionic 4

After updating the versions of Angular, Cordova, and Ionic, I started experiencing an issue with the tab icons displaying partially. Specifically, when my app loads with 4 tabs, only the first and third icons are visible. However, upon touching one of the ...

Utilize Azure Functions: Employ the Apollo Azure handler within an asynchronous function

Looking to incorporate some checks before executing the apollo handler function, I attempted to wrap it in an async function. However, when exporting the function as async, it consistently returns an empty response. functions.json { "bindings" ...

Unexplained Reference Error in Next.js Typescript: Variable Accessed before Initialization

I am currently working on an admin website and encountered the error Block-scoped variable used before its declaration.. I will provide details using images and code. This is my first time seeking help on StackOverflow. Error Message: Block-scoped variab ...

Jest encountered an error while attempting to parse the TypeScript configuration file

I've been working on setting up Jest with Babel and Typescript, following the guidelines provided here. However, when I run npm run test, I encounter the error message: Error: Jest: Failed to parse the TypeScript config file C:...jest.config.js` Th ...

No declaration file was located for the module '@handsontable/react' despite the presence of a 'd.ts' file

Embarking on a fresh project using vite+react+ts+swc by executing the command below as per the vite documentation. npm create vite@latest -- --template react-swc-ts Additionally, I integrated the handsontable library into my setup with the following comm ...

JS- Catching Errors Inside and Outside

Imagine having 2 catch blocks in your code: try { axios.get('https://example.com', {}) .then(function (responseOne: any) { return axios.post('https://example.com', {}, {}) }).then(async function (responseTwo: any) { return a ...

Modifying the version target of TypeScript code results in the TypeScript Compiler being unable to locate the module

After installing signalr via npm in Visual Studio 2019, I encountered an issue. When the target in my compiler options is set to ES6, I receive the error TS2307 (TS) Cannot find module '@microsoft/signalr.'. However, when I change the target to E ...

Why is my RxJS timer not waiting for the specified time?

I'm diving into the world of RxJS and trying to grasp its concepts. During some testing, I encountered a puzzling issue that has me stumped. Below is the snippet in question : let item = { id: 1, name: 'chair' }; const asyncItem = timer(20 ...

Utilize ngx-filter-pipe to Streamline Filtering of Multiple Values

Need assistance with filtering an array using ngx-filter-pipe. I have managed to filter based on a single value condition, but I am unsure how to filter based on multiple values in an array. Any guidance would be appreciated. Angular <input type="text ...

Can you explain the mechanics behind the functionalities of @angular and @type dependencies?

This inquiry may have been raised before, but I couldn't uncover all the solutions. If that's the case, my apologies. I have a good grasp on how package.json and dependencies / dev-dependencies function in Node applications. Currently delving i ...

An item whose value is determined by the specific type of key it possesses

Consider the following scenario: enum MouseType { GENERAL_USE = 1, SPECIALIZED_USE = 2, } enum KeyboardType { GENERAL_USE = 3, SPECIALIZED_USE = 4, } interface MouseSpecifications { buttons: number; dpi: number; } interface KeyboardSpecifica ...

Utilize FastClick for improved speed and response on

I have been trying to use FastClick in my TypeScript project with FastClick.d.ts. My TSC configuration uses "module: commonjs" and I am bundling everything with Webpack. However, I am having trouble referencing FastClick properly. When I try to import Fas ...

Angular unable to send object to HTML page

Struggling with learning angular, encountering new challenges when working with objects in different components. In two separate instances, try to implement two different mechanisms (microservice or service component serving an object directly). This speci ...

Dynamically loading components within an Angular application

I am tasked with displaying different components at specific times by iterating through them. Below is an example of how I have attempted to achieve this. The components I can use are determined by the server. <ngb-tabset [activeId]="1"> ...

The request to search for "aq" on localhost at port 8100 using Ionic 2 resulted in a 404 error, indicating that the

Trying to create a basic app that utilizes an http request, but facing challenges with cors in ionic 2. To begin with, modifications were made to the ionic.config.json { "name": "weatherapp", "app_id": "", "v2": true, "typescript": true, "prox ...

Angular 2: Creating a Reusable Object for Uniform JSON Structures

I am facing an issue with JSON data as I have 3 tables in my database named "dictionary" with the same structure but different column names: {"id":1,"test_1":"test"},{"id":2,"test_1":"lalala"} - first JSON {"id":1,"test_2":"****"},{"id":2,"test_2":"afe ...

Leverage TypeScript to access custom component properties and URL parameters from react-router-dom

In my react-router-dom setup, I have a route structured like this: <Route path="/result/:result" component={ResultsView} audio={audio} speechRecognition={speechRecognition} /> Furthermore, I have a component with specified props as follows ...

Creating a TypeScript schema with nested maps and arrays using Dynamoose

I'm currently in the process of developing a schema for a specific example: { "foods": [ { "fruits": [{ "apple": { "color": "red", ...

Is it possible to retrieve and utilize multiple Enum values in Typescript?

Combine enum values to retrieve corresponding enum strings. Consider the following scenario: enum EnumDays { NONE = 0, SUN = 1, MON = 2, TUE = 4, WED = 8, THU = 16, FRI = 32, SAT = 64, ALL = 127 } If I pass a value o ...

What is the process for importing WebAssembly functions into TypeScript?

I currently have a TypeScript project and am in the process of incorporating a WebAssembly Module to replace certain functionalities. Successfully importing the WebAssembly module involved moving the .wasm loading logic to its own .js file, which is then ...