Can a string be used to reference a type in Typescript?

Consider this scenario: I have created a set of interfaces that define the entities within my system:

interface Company {
  name: string
}

interface Employee {
  firstName: string
  lastName: string
}

Now, what I am looking for is a universal function that can retrieve these entities based on the interface specified as a string.

const company = findOne('Company', 1)
const employee = findOne('Employee', 2)

My question is, is it feasible to introduce a dynamic return type in the findOne function? This way, when we use it like shown above, the compiler recognizes company and employee as instances of Company and Employee respectively?

Answer №1

To achieve this, consider implementing an interface map type and deducing the first argument:

interface Organization {
  name: string
}

interface Staff {
  firstName: string
  lastName: string
}

type InterfaceMap = {
  Organization: Organization,
  Staff: Staff,
}

function findSingle<Key extends keyof InterfaceMap>(key: Key, number: number): InterfaceMap[Key] {
  return null as any
}

const organization = findSingle('Organization', 1) //  Organization
const staffMember = findSingle('Staff', 2) //  Staff

Try it out

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

Scrolling the mouse wheel on Angular 2 Typescript Highcharts Highmap

I'm currently exploring if it's possible to subscribe to the zooming event in a Highmap using Angular 2 with Typescript for Highcharts/Highmap, or possibly even to a mouse wheel scrolling event. @HostListener('scroll', ['$event&a ...

Looking to seamlessly integrate a CommonJS library into your ES Module project while maintaining TypeScript compatibility?

I am interested in creating a project with Typescript. The project is built on top of the Typescript compiler, so I am utilizing Typescript as a library, which I believe is a CommonJS library. Although the project is designed to run on Node (not in the bro ...

Tips on avoiding the conversion of the ✳ symbol into an emoji

My issue lies in my ✳ (Eight-Spoked Asterisk) symbol being converted to an emoji on iOS/android devices. Find more about the Eight-Spoked Asterisk Emoji here. Could someone guide me on how to prevent the normal symbol ✳ from being transformed into an ...

Guide to incorporating Bootstrap icons into an Angular application through programming techniques

Have you checked out the official bootstrap documentation for information on how to use their icons? https://i.stack.imgur.com/N4z2R.png I'm currently trying to understand the package and its usage. However, none of the options in the documentation ...

Encountering an error while implementing a Typescript addEventListener for keydown events

Struggling with adding and removing event listeners to HTML elements capable of focus, such as buttons. encountering a typescript error specifically related to the lines of code responsible for adding and removing the event listener: focusableElements.fo ...

Can a Typescript class type be defined without explicitly creating a JavaScript class?

I am exploring the idea of creating a specific class type for classes that possess certain properties. For example: class Cat { name = 'cat'; } class Dog { name = 'dog'; } type Animal = ???; function foo(AnimalClass: Animal) { ...

When I define a type in TypeScript, it displays "any" instead

Imagine a scenario where we have a basic abstract class that represents a piece in a board game such as chess or checkers. export abstract class Piece<Tags, Move, Position = Vector2> { public constructor(public position: Position, public tags = nul ...

Creating a mongoDB query that matches elements in an array of subdocuments with elements in a Typescript Array

In my database, I have stored various Events using mongoDB. Each event comes with multiple fields, including an array of genres, which consists of subdocuments like {genre and subGenre}. For instance, an event could be classified as {genre: "music", subGe ...

Oops! Something went wrong - it seems like there was an issue trying to access the property 'Date/Heure' of

When my web application uploads a .mes file, it retrieves data and manipulates it to insert into an Object. Initially, the object is empty, but after uploading the file, the data appears. I am trying to display the 'date' obtained from the .mes ...

The compatibility issue between Tailwind CSS and Material UI has been identified in the latest version of Next, version 14.0

Currently, I am working with Next 14.0.2 alongside Material UI and Tailwind CSS for my Frontend development tasks. However, I've run into some challenges regarding styling components. One specific issue I faced was when setting a button to navigate to ...

Angular 10 recommends utilizing the "forEach" method in place of "map" since the return value of "map" is not being utilized in this specific context

I encountered the following error message: Consider utilizing "forEach" instead of "map" since the return value is not being utilized in this case. declare const require: { context(path: string, deep?: boolean, filter?: RegExp): { keys(): string[]; (id: ...

The sum is being treated as a concatenation instead of an addition in this case

Why is the somma value showing the concatenation of totaleEnergetico and totaleStrutturale instead of a sum? RiepilogoCombinatoStComponent.ts export class RiepilogoCombinatoStComponent implements OnInit { constructor() { } interventi: AssociazioneI ...

Can we employ the spread operator in generic parameters?

For instance, when working with ReactQuery's useQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>, I aim to achieve the following: type QueryTypeParams = [Record<string, number>, u ...

What are the best practices for implementing MapLabel in an Angular project?

I need help displaying text on top of multiple polygons on a map. I've heard that Map Label can help with this, but I'm having trouble implementing it and can't find any NPM resources. Here is the Stack Blitz URL for reference: https://stac ...

Angular - The 'options' property is not found in the 'HTMLOptionElement' type

Currently, I am attempting to modify the choices in a dropdown menu based on the selection made from another dropdown. This problem led me to come across a helpful resource on a website called "Form Select Change Dynamic List Option Elements Tutorial". How ...

Another option to avoid using complicated else if chains

I'm facing a challenge with a function that returns a value known as user_id. It involves multiple conditions that need to be checked. First condition: Verify the service variable Second condition: If not found, retrieve user_id from local storage ...

Executing the outer function from within the inner function of a different outer function

Imagine this scenario: function firstFunction() { console.log("This is the first function") } secondFunction() { thirdFunction() { //call firstFunction inside thirdFunction } } What is the way to invoke firstFunction from thirdFunction? ...

Adjust Column Title in Table

Is it possible to customize the column headers in a mat-table and save the updated value in a variable? I've been looking for a solution to this but haven't found one yet. ...

Angular Animation not smoothly transitioning on Internet Explorer 11 and Firefox, but functioning correctly on Chrome

Chrome seems to be handling my Angular animation attached to a div (where the height goes from 0 to '*') just fine. I've made sure to import all necessary polyfills and install web-animations-js. However, when it comes to IE and Firefox, th ...

Challenge with the scope of 'this' in Typescript

Whenever I invoke the findFromList function from a component, it triggers this particular error message: ERROR TypeError: Cannot read property 'searchInArray' of undefined at push../src/app/shared/services/filter.service.ts.FilterService ...