Is there a way for me to deduce types dynamically?

Is there a way to dynamically infer types, similar to a union type?

I am trying to register multiple elements from different parts of the code using a method like registerElement(...), but I am struggling with inferring these new types in TypeScript. This leads to errors like

Type '"pack"' is not assignable to type '"common"'
.

In the desired behavior, I expect that when a new element is registered, such as "pack", it becomes available for use. Since I do not know how many elements there will be and they can be added or removed with new code, I do not want to hard code types like:

type ElementTypes = Common | Pack | ...N

I understand that TypeScript infers types at compile-time, not runtime, and the example below does not work.

interface BaseElement<T, C> {
    name: T,
    nested: C[]
}

interface Common extends BaseElement<'common', string> {}

const common: Common = {
    name: 'common',
    nested: []
}

const myElements = {common}

type ElementTypes = keyof typeof myElements

const foo: ElementTypes = 'common'; // Ok.

// Assign a new element
interface Pack extends BaseElement<'pack', Common> {}

const pack: Pack = {
    name: 'pack',
    nested: []
}

Object.assign(myElements, {pack});
const bar: ElementTypes = 'pack'; // Not working.

Answer â„–1

During compilation, TypeScript infers types and not during runtime. The example provided below does not function as expected.

This misunderstanding of TypeScript stems from the fact that what you are asking for is impossible.

Since it's uncertain how many elements will be present, and they can be dynamically added or removed with new code, hard coding types like this is not considered:

If the full range of possible string literals is known, then a union of all those types is indeed necessary. This approach accurately models the problem. It doesn't matter if at runtime an object/array may only contain some of these types, as the type system only focuses on possibilities rather than actual content—something it cannot ascertain since that information isn't available at runtime. You might wonder how you could utilize one of these types independently. Essentially, through runtime code. Refer to type narrowing.

If any arbitrary string could potentially be added at runtime (e.g., through user input), it's impractical to strongly type the array/object contents to such precision. In such cases, simply use string instead.

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

Angular 10 introduces a new approach to handling concurrency called "forkJoin"

Here is the code I have: async getBranchDetails() ----component method { let banks = this.bankDataService.getBanks(); let branchTypes = this.branchDataService.getBranchTypes(); forkJoin([banks,branchTypes]).subscribe(results => { ...

Combining Arrays Together in TypeScript

I am in need of a solution to merge two arrays into one using TypeScript. First Array Object: export interface Item{ Label : string, Code : string, Price : number, } Second Array Object: export interface Amou ...

Move information from one page to another

I'm currently using Ionic 2 and attempting to pass data from one page to another. Specifically, I want to transfer the data of a selected list item from the first page (quickSearch) to the second page (quickSearchDetail). To illustrate this, refer to ...

Utilize Ngrx to keep an eye on specific items within the store

If we consider an interface called INotification: export interface INotification { id: number; DateReceived: number; Title: string; Message: string; Tipology: string; isRead: number; } and a reducer system. In the component, it&ap ...

Is there a point in bundling NPM packages if they are ultimately going to be bundled by the project

I'm in the process of creating a TypeScript package for publication on NPM. My plan is to utilize this package in upcoming web development endeavors, most likely utilizing Vite. As I look ahead to constructing a future website with this module, I am c ...

Tips for accessing and manipulating an array that is defined within a Pinia store

I have set up a store to utilize the User resource, which includes an array of roles. My goal is to search for a specific role within this array. I've attempted to use Array functions, but they are not compatible with PropType<T[]>. import route ...

Unable to utilize vue-cookies library in TypeScript environment

I have integrated vue-cookies into my app in the main.ts file: import VueCookies from 'vue-cookies'; ... const app = createApp(App) .use(IonicVue) .use(router) .use(VueCookies,{ expires: '30d', }); Despite adding the cookie v ...

Is it possible to define a variable within an array declaration?

I am trying to construct an array for the week, with each element being an instance of my "work hours" class. However, when attempting to define them within the array directly, I encounter an error. Upon inspecting the JS file, I noticed that the array is ...

What is the process for automatically initiating a service when importing a module in Angular?

I am curious about how I can automatically run a service within a module upon importing it, without the need for manual service injection and execution. This functionality is similar to how the RouterModule operates. @NgModule({ imports: [ Browser ...

In Typescript, null values are allowed even when the type is set to be non-nullable

Can someone explain why the code below allows for null in typescript, even though number is specified as the type: TS playground // Not sure why null is accepted here when I've specified number as the type const foo = (): number => 1 || null ...

Getting the Class name in Typescript

How can you retrieve the class name from within a Class in typescript? For instance, consider this code snippet: export class SomeRandomName extends AbstractSomething<SomeType> implements OnDestroy { className = 'SomeRandomName'; Is th ...

Develop an item with a function that takes an input of the identical type as a variable within the item itself

I am facing a challenge with managing an array of objects that represent commands for my game. Each object includes an input field to define the types of arguments expected by the command. The purpose of this setup is to enable validation on the arguments ...

What is the best way to loop through the keys of a generic object in TypeScript?

When I come across a large object of unknown size, my usual approach is to iterate over it. In the past, I've used generators and custom Symbol.iterator functions to make these objects iterable with a for..of loop. However, in the ever-evolving world ...

What is preventing me from consistently accessing the Type Definition while my cursor is on a JavaScript/TypeScript parameter name in VS Code, and what are some strategies I can use to overcome this issue?

Imagine I have the following code snippet in my VS Code: type T1 = { x: number }; type T2 = { x: number } & { y: string }; function foo(arg1: T1, arg2: T2) {} If I place my cursor on arg1 and go to the type definition (either through the menu or a sh ...

Creating a universal wrapper function to serve as a logging tool?

Currently, I am working on a generic JS function that can wrap any other function. The purpose of this wrapper is to execute the wrapped function, log the input and output events, and then return the output for "transparent" logging. However, as I attempt ...

Accessing HTTP data through a function instead of using ngOnInit in Angular is a more efficient approach

Trying to retrieve data from a service using setInterval has posed an issue for me. When I call the service from ngOnInit, everything functions as expected. However, when attempting to call it from any other function, an error occurs: "ERROR TypeError: Ca ...

ngx-datatables in Angular is experiencing issues with its filtering options

Having trouble implementing a filter option in ngx-datatables for all columns. I've written the code but it's not functioning correctly. Can anyone help me identify where I went wrong and find solutions? app.component.html: <label> Nam ...

Enhancing search capabilities in Angular 8.1.2 by filtering nested objects

I am in need of a filter logic similar to the one used in the example posted on this older post, but tailored for a more recent version of Angular. The filtering example provided in the older post seems to fit my requirements perfectly, especially with ne ...

Error: Typescript error at line 18 in app.ts - Cannot locate the 'server' namespace

Check out this straightforward code snippet: "use strict"; import * as express from "express"; class Server { public app: express.Application; public static start(): Server { return new Server(); } constructor() { this. ...

Ensure that only numbers with a maximum of two decimal places are accepted in Angular 2 for input

On my webpage, there are several input boxes where users can enter numbers. I need to prevent them from entering more than two decimal places. Although I tried using the html 5 input Step="0.00", it didn't work as expected. I am open to any TypeScri ...