Dynamic Variable Typing in TypeScript: Adjusting variable types on the fly

I am working with 2 variables named locals and visitants. These variables can either be of type PlayerDto or TeamDto, which will be determined by a third variable called competitor_type. If competitor_type is player, then I need to assign a list of Players to locals and visitants, otherwise, I need to assign a list of teams.

I am currently using "any" to solve this.

locals: any
teams: any

Is there a more efficient way to handle this situation?

Answer №1

If you want to organize the different versions in an Object to better specify the types, you can follow this approach:

let state: {
  type: "player";
  locals: PlayerDto[] | undefined;
   visitants: PlayerDto[] | undefined;
} | {
  type: "team";
  locals: TeamDto[] | undefined;
  visitants: TeamDto[] | undefined;
} = { type: "player" };

This ensures that your code will always be typesafe:

 if(state.type === "player") {
   state.locals // is of type PlayerDto[]
 }

 state.locals // is of type PlayerDto[] | TeamDto[]

If you need to change the type, simply do:

 state = { type: "team" };

After this, you can freely reassign values to state.locals and state.visitants.

Answer №2

Creating a type based on a variable is not possible, but you can specify the possible types for a variable using a union type (|). Here is an example:

let locals: PlayerDto | TeamDto
let visitants: PlayerDto | TeamDto

When working with this, it is often necessary to check the type using instanceof

if(locals instanceof PlayerDto) {
  // Do something for PlayerDto
}
else if(locals instanceof TeamDto) {
  // Do something for TeamDto
}

Answer №3

Utilize the union type feature.

let locals: PlayerDto[] | TeamDto[];

By using this approach, you are specifying that locals can be a collection of either PlayerDto or TeamDto.

For more information on union types and other advanced type concepts, check out: https://www.typescriptlang.org/docs/handbook/advanced-types.html

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

Using Boolean as a prop in Vue.js

Creating a Vue form to ask a question involves making a component: <template> <div class="flex flex-col items-center justify-center gap-2"> <div class="flex w-[80%] items-center justify-center gap-2 rounded-3xl p-2" ...

Group By feature in AngularJS

Hey there, I'm trying to display a table from the code provided below. The issue I'm facing is with grouping by name. Here's how I want the view to appear: Shareholder | Preferred Stock | Common Stock | Options | Percentage | |----------- ...

Combine a string and integer in JavaScript without using quotation marks between them

Is there a way to concatenate a string and an integer in JavaScript without getting the ": Here is the code snippet: "<agm-map latitude=" + response.latitude + " longitude=" + response.longitude + "></agm-map>"; What it currently results in: ...

"Patience is key when waiting for the alert dialog response in Vuetify

I currently have a reusable component called Alert.vue. <v-dialog v-if="alertDict" v-model="alertDict.showDialog" max-width="460"> <v-card> <v-card-title>Title</v-card-title> & ...

Is Turbopack compatible with frameworks other than NextJs?

With its impressive speed, it would be great to utilize it in various outdoor projects like Vite. Unfortunately, there does not seem to be much information about it on their website I also checked out https://github.com/vercel/turbo but the details were s ...

Input the chosen icon list values into a designated box

As a beginner in the world of Javascript, I am venturing into creating a password generator that involves using icons. The concept is simple - by clicking on any number of icons from a list, the corresponding hex code will be displayed in an input box. The ...

Combining functions in React is a powerful way to create

Is there a way to create a single function that combines handleSelectAll and handleSelectNone for toggling options in a list of categories? Instead of using a toggle (on/off) approach, I believe having separate buttons for Select All and Select None is mor ...

Using the spread operator in React to distribute JSX elements within a map function

I am struggling with mapping over an array within another array to create a Picker and am having difficulty returning JSX elements instead of an array of JSX elements. Here is the code example: {modelA.map((mA) => { const pickerItems = mA.modelB.m ...

Obtain the dynamic $scope variable within the HTML structure

When creating numerous directives with dynamic scope variables initialized in the link functions, accessing these values within the directive templates can get tricky. For example: // link: function(scope, ele, attr){ scope.key = scope.somevar + 's ...

Check if the element is not present in the array, then add it to the array

I am attempting to generate an array in JavaScript with unique elements extracted from a JSON feed. My thought process is possibly too influenced by PHP, where a simple script like the one below would suffice: $uniqueArray = array(); foreach($array as $ke ...

Here is a unique version: "A guide on centering a carousel item in jquery upon being clicked."

Does anyone know how to center the item I click in a carousel? I've searched high and low for a solution but couldn't find a clear answer. Can someone please assist me with this? This is what I have tried so far: http://jsfiddle.net/sp9Jv/ Here ...

Can you provide me with the sequelize query that is equivalent to this raw query?

Retrieve the ID from the offers table where the user ID is not equal to '2' and the ID is not present in the list of notified offers for user '2'. ...

Encountering an issue with npm start when attempting to launch the local host server for a React.js project

Encountering an issue with npm start Error message: 'Equipment' is not recognized as a command, operable program or batch file. internal/modules/cjs/loader.js:983 throw err; ^ Error: Module not found 'C:\Users\Home\Deskto ...

Creating a TypeScript definition file to allow instantiation of a module

I'm encountering an issue with creating a declaration file for an existing module. When using JavaScript, the module is imported using the following syntax: var Library = require('thirdpartylibs'); var libInstance = new Library(); I have ...

Compiling fails when creating an object literal with a generic key

I am attempting to accomplish the following task. function createRecord<T extends string>(key: T) : Record<T, T> { return {[key]: key}; // Type '{ [x: string]: T; }' is not assignable to type 'Record<T, T>' } Howe ...

What is the best way to implement a delay before calling the owlCarousel function?

Is there a way to delay calling the owlCarousel function for 5 seconds? I attempted the following: $(document).ready(function(){ setInterval(function(){ $(".demo-slide").owlCarousel(); },5000); }); However, I encountered ...

Run the js.erb code only when a certain condition is met

I'm feeling a bit lost when it comes to CoffeeScript and JS. I have a quick editing feature that sends an AJAX request and updates the database. Currently, I manually change the edited content's place and display it, but it feels like a workaroun ...

How to access webpack's require.context feature on the development server

In my webpack development configuration, I have set up a mocked backend using Express. Following an example from the DevServer Docs, my setup looks something like this: module.exports = { // ... devServer: { setupMiddlewares: (middlewares, devServe ...

Yep, implementing conditional logic with the `when` keyword and radio buttons

I seem to be encountering an issue with my implementation (probably something trivial). I am utilizing React Hook Form along with Yup and attempting to establish a condition based on the selection of a radio group. The scenario is as follows: if the first ...

change the property of an object in JavaScript

Trying to make changes to an item in an object (result of finding in a collection). Collection name: {}, date: {} Examples of documents in the collection [ {name: "pedro", date: "2018/01/01"}, {name: "juan", date: "2018/02/02"} ] Working with ...