The error message in TypeScript is indicating that the property 'x' is not found in the type '{}', which is required for a computed key

Description of a Typescript fragment:

enum Field {
    age,
    bugs,
}
interface Foo {
    number_age: number;
    number_bugs: number;
}

function createFoo():Foo {
    let obj = {};
    let index = 0;
    for (let key in Field) {
        obj['number_'+key] = index++;
    }
    return obj;
}

An error is thrown during compilation:

$ tsc test.ts 
test.ts(16,5): error TS2322: Type '{}' is not assignable to type 'Foo'.
  Property 'number_age' is missing in type '{}'.

However, obj is guaranteed to contain 'number_age' at runtime. How can the compiler be made aware of this or how can the code be modified to compile successfully?

Answer №1

To specify that the variable ret will represent a Foo element, you can use the keyword as

enum Field {
    age,
    bugs,
}
interface Foo {
    number_age: number;
    number_bugs: number;
}

function makeFoo():Foo {
    let ret = {} as Foo;
    let i = 0;
    for (let key in Field) {
        ret['number_'+key] = i++;
    }
    return ret;
}

Refer to the documentation on type assertions:

There may be instances where you have more knowledge about a value than TypeScript. This can occur when you know the specific type of an entity.

Type assertions allow you to inform the compiler that you are aware and confident about the type of a value. Unlike type casts in other languages, type assertions do not perform any data restructuring or runtime actions. They are solely used by the compiler. TypeScript assumes that as a programmer, you have conducted any necessary validations.

Type assertions can take two forms. One is the “angle-bracket” syntax:

let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;

The other form is the as-syntax:

let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;

Both examples are functionally equivalent. The choice between them is typically based on personal preference. However, when working with TypeScript and JSX, only as-style assertions are permitted.

Answer №2

You seem to be straying quite far from the original plan here (creating properties number_0 and number_1 on Foo, was that intentional?) so it might be more trouble than it's worth to try to fully typecheck this code. It may be best to just go with any:

function createFoo(): Foo {
    let result: any = {};
    let i = 0;
    for (let prop in Field) {
        result['number_' + prop] = i++;
    }
    return result;
}

Answer №3

it's suggested to utilize the casting operator <TYPE>

enum Category {
    size,
    errors,
}
interface Bar {
    size_number: number;
    errors_number: number;
}

function createBar():Bar {
    let result = {};
    let index = 0;
    for (let label in Category) {
        result['number_'+label] = index++;
    }
    return <Bar>result; // At this point
}

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 error message indicates that the property 'current' is not found in the type '[boolean, Dispatch<SetStateAction<boolean>>]'

During my React/Typescript project, I encountered an issue involving cursor animations. While researching the topic, I stumbled upon a CodePen (Animated Cursor React Component) that functioned perfectly. However, when attempting to convert it into a Types ...

The click method in the Angular unit test does not seem to be executing successfully

I'm facing a seemingly simple issue where I am unable to confirm that a click handler is being triggered on my component. header.component.ts import { Component, EventEmitter, OnInit, Output } from '@angular/core'; @Component({ selecto ...

Retrieve a particular item using the NGXS selector and incorporate it into the template

I am retrieving stored configuration settings from an API. Each setting includes an 'ID' and several properties like 'numberOfUsers', etc. I am utilizing NGXS for managing the state. My goal is to specifically fetch the 'numberOf ...

Why am I unable to use a string as the src in next/image component?

After importing the Image module with the code import Image from "next/image";, I encountered an error that states: The type '{ src: string; }' cannot be assigned to type 'IntrinsicAttributes & ImageProps'. The type &apo ...

Issue with displaying response data from Angular API in the template

I am retrieving categories from the backend and trying to display them in a table. However, there seems to be an issue with my code as no data is showing up in the table. Although the getFournisseurs method is successfully fetching 5 items from the backen ...

Tips for efficiently resolving and compiling a bug within an NPM package, ensuring it is accessible to the build server

This question may seem a bit unconventional. I am currently using an npm package that includes built-in type definitions for TypeScript. However, I have discovered a bug in these definitions that I am able to easily fix. My goal is to make this updated ve ...

Transforming API response data into a Typescript object using React mapping

When I make an API call, the response data is structured like this: [ { "code": "AF", "name": "Afghanistan" }, { "code": "AX", "name": "Aland Islands" } ...

Issues arise with Shared Module imports not functioning properly within Shared components following an upgrade to Angular 9

I recently updated my project to the following versions: Node from 11 -> 12 Angular from 8 -> 9 After the upgrade, I started encountering compile time errors in my application. The application consists of numerous shared components that are declare ...

Lint found an issue: The variable 'post' has been defined but is not being utilized in the code

Within my codebase, I have included the following import: import { post } from '@loopback/rest' This is how I am utilizing it in my project: export class MyClass { @post('/example/test', {}) } Unfortunately, a lint error has been de ...

Leveraging the power of TypeScript and Firebase with async/await for executing multiple

Currently, I am reading through user records in a file line by line. Each line represents a user record that I create if it doesn't already exist. It's possible for the same user record to be spread across multiple lines, so when I detect that it ...

When converting an object into a specific type, the setter of the target type is not invoked

Imagine a scenario with a class structured like this: class Individual { private _name: string; get Name(): string { return this._name; } set Name(name: string) { this._name = name; } } Upon invoking HttpClient.get<Individual>(), it retrieve ...

Provide an immutable parameter to a function that will not cause any changes

Looking to develop a function named batchUsers, requiring a parameter of type readonly string in order to create a DataLoader. However, when calling the User.findBy function within my batchUsers function, it's causing issues due to conflicting paramet ...

Utilizing ngx-logger Dependency in Angular 6 for Efficient Unit Testing

Have you ever attempted to test classes in Angular that rely on ngx-logger as a dependency? I am looking for guidance or examples of how this can be achieved using testing frameworks such as Jasmine. It seems there are limited resources available on mock ...

What is the best way to transform an Observable array containing objects into an Observable that emits the data contained within those objects?

Encountering an error: Error: Type 'Observable<Country[]>' is not assignable to type 'Observable'. Type 'Country[]' is missing properties like name, tld, alpha2Code, alpha3Code and more.ts(2322 The issue might be due ...

Create a checklist with unique identification, value, and description by utilizing an array of objects

Utilizing React with Typescript, I am tasked with constructing the React component MultiSelectCheckBoxes by supplying an array of Objects of type Color to the constructor: The structure for a checkbox list should be like this: const options = [{ "id": ...

Incorporating XMLHttpRequest in my React Typescript App to trigger a Mailchimp API call, allowing users to easily sign up for the newsletter

My website needs to integrate Mailchimp's API in order for users to subscribe to a newsletter by entering their email into a field. I am looking to implement this without relying on any external libraries. To test out the functionality, I have set up ...

Struggling to properly import the debounce function in ReactJS when using TypeScript

I am facing an issue while trying to properly import the debounce library into my react + typescript project. Here are the steps I have taken: npm install debounce --save typings install dt~debounce --save --global In my file, I import debounce as: impo ...

What is the rationale behind permitting surplus properties in Typescript interfaces even though all properties are declared as optional?

Exploring the code snippet... interface Options { allowed?: string; } function test(options: Options) { return options; } const options = { allowed: 'allowed', notAllowed: 'notAllowed', }; test(options); // no error thrown ...

Guide on obtaining Elastic search documents in the specified order of identifiers

Given a specific order of document IDs [1, 4, 2, 5] and some filtering criteria { match: {...} }, what is the most efficient method to ensure that the resulting documents are retrieved in the desired order [1, 4, 2, 5]? Here is an example of a sample docu ...

Issue encountered while declaring a variable as a function in TSX

Being new to TS, I encountered an interesting issue. The first code snippet worked without any errors: interface Props { active: boolean error: any // unknown input: any // unknown onActivate: Function onKeyUp: Function onSelect: Function onU ...