Entering information into fluctuating object fields

Suppose I have a dynamic object with a union type:

  data: {[key in 'num' | 'str' | 'obj']: number | string | object};

I set the object properties as follows:

  data.num = 1;
  data.str = 'text';
  data.obj = {};

Everything seems to be working fine. However, when I try to access:

  data.num

and use this value to perform operations like summing up all data.num properties, I face an issue because the compiler indicates that data.num is of a union type. How can I explicitly specify to the compiler that data.num is of type number? I am aware of using as, but I find it to be less elegant. I have searched for solutions on platforms like Stack Overflow, Medium, and other programming sites without success.

Edit:

This was just an example. In reality, I have an array of objects that need to be grouped based on one of their Enum properties and then mapped. Here's how I'm approaching it:

Object.values(Enum).forEach(
    enum => subjects[enum].next(
        array
            .filter(object => object.type === enum)
            .map(object => object.payload)
    )
);

I thought creating an object to store all the subjects would be the best approach, however, this results in all the subjects inside the object being of a union type. If enum values change for any reason, I would only need to update the enum type, nothing more.

Answer №1

Considering the limitation of only having 3 keys, wouldn't it be more practical to design an interface that explicitly states the type of each key?

interface Bar {
    num: number;
    str: string;
    obj: object;
}

const bar: Bar = {
    num: 1,
    str: 'text',
    obj: {},
}

console.log(bar.num); // (property) Bar.num: number
console.log(bar.str); // (property) Bar.str: string
console.log(bar.obj); // (property) Bar.obj: object

Check it out on TypeScript playground.


From analyzing the code you've shared in the comments, it appears that you are using an enum as a key. TypeScript may require manual assistance in assigning the correct type to the key:

enum AlertType {
  ERROR = "ERROR",
  WARNING = "WARNING",
  INFO = "INFO",
  SUCCESS = "SUCCESS"
}

interface Team {
  name: string;
  members: object[];
}

interface ErrorAlert {
  details: string;
}

interface InfoAlert {
  message: string;
}

interface Baz {
    [AlertType.ERROR]: ErrorAlert[],
    [AlertType.WARNING]: InfoAlert[],
    [AlertType.INFO]: Team[],
    [AlertType.SUCCESS]: Team[]
}

const baz: Baz = {
    [AlertType.ERROR]: [],
    [AlertType.WARNING]: [],
    [AlertType.INFO]: [],
    [AlertType.SUCCESS]: []
}

console.log(baz[AlertType.ERROR]); // ErrorAlert[]
console.log(baz[AlertType.WARNING]);    // InfoAlert[]
console.log(baz[AlertType.INFO]);  // Team[]
console.log(baz[AlertType.SUCCESS]);  // Team[]

View example on TypeScript Playground.

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

Generating TypeScript Type Definitions for dynamic usage

In my client server application, I use REST calls for communication. To avoid using the wrong types by mistake, I have defined all RestCalls in a common file (excerpt): type def<TConnection extends Connections> = // Authentication ...

How can Vue Router be integrated with Vue.JS SSR?

Despite reading up on SSR documentation, I am struggling to make it work (I feel lost). I created the project with Vue CLI using 'vue new frontend'. I opted for typescript and configured all settings in package.json. Additionally, I am utilizing ...

What is the process for adding custom text to create a .d.ts file using the TypeScript compiler?

In my endeavor to develop a javascript module using TypeScript that is compatible with ES5 browsers and NodeJs modules, I have encountered a dilemma. I wish to avoid using import and export in TypeScrtipt as it creates dependencies on SystemJS, RequireJS, ...

What is the role of the handleSubmit parameter in React Hook Form?

I'm encountering an issue with TypeScript in the handleSubmit function. To start off, I am accessing the handleSubmit function through the useForm hook: const {handleSubmit, control, watch, reset} = useForm() Next, I define a submit function: con ...

How can Mui typescript be extended with a unique wrapper that includes a `component` property?

I recently created a unique wrapper component: import Box, { BoxProps } from "@mui/material/Box"; type CustomWrapperProps = { id: string } & BoxProps const CustomWrapper = (props: CustomWrapperProps) => { const {id, children, ...rest ...

Proper method of retrieving a property as a designated type within a union type

I have a scenario where I need to return a specific property from a function in various parts of an application. This property can fall into one of two categories, each with string literal properties. One category is an extension of the other. How can I ...

Capture Video on iOS devices using the MediaRecorder API and display it using HTML5 Video Player

Issue: I am facing an issue where I cannot record video or get a video stream from the camera on iOS through my Angular web application built using ng build. Investigation: In my investigation, I explored various websites that discuss Apple iOS features ...

Dynamic autocomplete in Oclif utilizing an HTTP request

Is it feasible for Oclif to support the functionality of making API calls to retrieve values for autocomplete? Consider this scenario: A database stores multiple users information Upon typing show users <Tab> <Tab>, the CLI triggers an API ca ...

What are some strategies for exporting methods without resorting to the use of import * as ...?

Imagine having a file structured like this: // HelperFunctions.ts export const dateFormat = 'MM/DD/YYYY'; export const isEmpty = (input: string | null | undefined): boolean => { if (input == null) { return true; } if (!in ...

Ways to solve VScode gutter indicator glitches after switching text editors?

When my active function is running, I have a specific updateTrigger that ensures certain actions are taken when the activeTextEditor in vscode changes: const updateTrigger = () => { if (vscode.window.activeTextEditor) { updateDecorations(con ...

Karma Error: Unexpected token import in Angular 2 - Uncovering a Syntax Error

I've been exploring this insightful tutorial on https://www.youtube.com/watch?v=yG4FH60fhUE and also referencing https://angular.io/docs/ts/latest/guide/testing.html to create basic unit tests in Angular 2 and ensure the proper setup of Karma. I encou ...

Connecting the mat-progress bar to a specific project ID in a mat-table

In my Job Execution screen, there is a list of Jobs along with their status displayed. I am looking to implement an Indeterminate mat-progress bar that will be visible when a Job is executing, and it should disappear once the job status changes to stop or ...

Encountering an issue while trying to import the instanceMethods function within Sequelize

In a file, I have written a function and exported it like this: export function foo(params...) { // do something } When initializing the model, I imported the function in the following manner: import { foo } from "../path/..." instanceMethods: { foo ...

PrimeNG Template not showing the form

I have integrated a form into PrimeNG's turbotable to allow users to create a new entry (group) in the table located within the footer. However, the form is not being displayed as expected. Can you help me troubleshoot this issue? <ng-template pTe ...

Utilize mapping to object and preserve type inference

I am currently developing a function that utilizes a map function to map objects. interface Dictionary<T> { [key: string]: T; } function objectMap<TValue, TResult>( obj: Dictionary<TValue>, valSelector: (val: TValue) => TResult ...

Transforming TypeScript declaration files into Kotlin syntax

Has there been any progress on converting d.ts files to Kotlin? I came across a post mentioning that Kotlin developers were working on a converter, but I am unsure about the current status. I also found this project, which seems to be using an outdated c ...

I encountered an issue while trying to implement a custom pipe using the built-in pipe

My custom pipe seems to be functioning well, except for the built-in pipes not working within it. I've imported Pipe and can't figure out what could be causing the issue. Below is the code with the errors: import { Pipe, PipeTransform } from &a ...

Ways to obtain the file path of the compiled worker.js loaded from the worker loader, along with its hash

Currently, I am working on a TypeScript React application that utilizes Babel and Webpack for compilation. I have implemented a rule to load my worker with the following configuration: config.module.rules.unshift({ test: /gif\.worker\.js$/, ...

Unit test: Using subjects instead of observables to mock a service and test the change of values over time results in TypeScript throwing error TS2339

I have a unique scenario where I have implemented a service that accesses ngrx selectors and a component that utilizes this service by injecting it and adjusting properties based on the values retrieved. For unit testing purposes, I am creating mock versi ...

How can a TypeScript object be declared with a single value assignment to itself?

Whenever I try to declare an object and assign a key to itself, I encounter errors. I have attempted different methods, but the error persists. const a = { d:123, a:a//<-TS2448: Block-scoped variable 'a' used before its declaration. } co ...