Is there a way to allow a property in a Javascript Object to accept multiple values in Typescript?

Suppose I define a new Object type:

interface NEWOBJECT {
    name: {};
}

Is it possible to have the 'name' property in NEWOBJECT be able to accept either 'name1' or 'name2', allowing me to create instances of NEWOBJECT with different names as the property value?
For example, like this:

var object1: NEWOBJECT = {name1: {}};
var object2: NEWOBJECT = {name2: {}};

Thank you.

Answer №1

Affirmative

type FRESHITEM = {
  [X in 'item1' | 'item2']?: {};
}

I regret to inform you that this setup still allows for both properties to be present or absent, so I recommend taking a more precise approach using union types instead.

interface FRESHITEM1 {
  item1: {};
}

interface FRESHITEM2 {
  item2: {};
}

type FRESHITEM = FRESHITEM1 | FRESHITEM2;

Ensure your TypeScript is up-to-date.

Answer №2

When assigning a type, it is essential to use properties with identical names. However, you have the flexibility to define optional properties as well. This allows you to assign your variable with any of these optional properties.

interface CUSTOMOBJECT {
    property1?: {};
    property2?: {};
}

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

Utilize RSelenium to showcase all rows in the display

I am encountering an issue while trying to extract data from the following website: . On this website, there is a table consisting of 1874 rows. Despite my efforts to scrape it, I was only able to retrieve the first 10 rows due to the default lengthMenu ...

Issue with redirecting to another link in Angular routing

After numerous attempts, I finally managed to configure the adviceRouterModule correctly. Despite extensive research and Google searches, I couldn't quite crack it. Here is the configuration for my AdviceRoutingModule: const adviceRouters: Routes = ...

Rails 4 does not properly handle the execution of Ajax responses

Currently, I am incorporating ajax functionality within my Rails application. Within the JavaScript file of my application, the following code snippet is present: $('#request_name').on('focusout', function () { var clientName ...

How can one obtain a distinct identifier retroactively?

One thing that I am working on is changing button images upon clicking, but this isn't the main issue at hand. Each button corresponds to unique information retrieved from the database, and when clicked, the button should change and send the appropria ...

What is the process of looping through an object in Angular to display this specific user interface?

Currently, I have an object that I need to iterate using *ngFor in order to display the UI as shown in the image link provided below. However, I am encountering difficulties when trying to separate it into different sections. Below is my Object: [ { " ...

What is the best way to display information using axios.get?

I am currently working on a small project with PHP and Axios. I am attempting to display data in an HTML table using the v-for directive, but I am facing issues as I receive server feedback. Although I am able to retrieve the JSON response successfully, wh ...

Retrieving ng-pattern as a variable from a service

Hey there! I'm currently working on an application that requires extensive form validation across multiple pages. To streamline this process, I am attempting to extract validation patterns from a service used among the controllers. However, I've ...

Resolving Cross-Domain Ajax for Improved API Performance

In the midst of developing an infrastructure to support a gaming platform that will cater to a large user base, performance is our top priority. We are striving to parallelize the architecture by running APIs, databases, and applications on separate server ...

Creating a SVG polygon using an array of points in JavaScript

Consider the following array containing points: arr = [ [ 0,0 ], [ 50,50 ], [ 25,25 ], ]; I would like to create an SVG polygon using this array. Initially, I thought the code below would work, but it doesn't: <polygo ...

Creating a Schema for an Inclusive Array Type in JsonSchema

Imagine you have the following type: type oneOfTwoPossibleArrays = | [1, 2] | [3, 4] If you were to create a schema for it, what would it look like? This is my initial attempt that didn't work as expected: <Edit: this code works with aj ...

Connect the keys from one enum to either keys or values in another enum

When working with the code below, it is important that the keys of PropertiesNamesInDataBase align with those in User.Keys. While the values of PropertiesNamesInDataBase are used in the backend, it is crucial for uniformity that the names match in the fron ...

A TypeScript generic function designed to accept either two arrays or two objects, but not a combination of both

Currently, I am creating an extend function in TypeScript that has the capability to: Update the first object with the keys/values of the second when given two objects. Append the elements of the second array to the first array when provided with two arr ...

Firebase Cross-Origin Resource Sharing (CORS) and IP range whit

Is there a way to whitelist two IP ranges in order to access my firebase cloud functions? I believe it should be possible to define them within this code snippet: const cors = require('cors')({ origin: true }); I tried searching on Google f ...

The element is implicitly declared as having an 'any' type due to the fact that an expression of type 'any' cannot be utilized to index type '{}'

I have a variable initialized with properties like this: const decoded = JSON.parse(nk.binaryToString(message.data)); const matchStateChanges = { humans: {}, ball: {}, } const { name } = decoded // for example, a string like "Player1" matchStateChang ...

Utilizing jQuery to format HTML code and set it as the text in a Textarea

I am currently working on populating the text for my Textarea using JavaScript (jQuery), as I need to include a variable from JS in it. This is what I have been doing: $("#txt_banner1").text( '<a href="'+producturl+'">< ...

Utilize jQuery to track and record AdWords conversions

I have noticed a number of inquiries regarding tracking Adwords conversions with jQuery on this platform. However, it appears that there is no definitive solution yet. My attempt at recording a conversion involves the code below following the submission o ...

Stop the execution of jQuery ready handlers

I am facing a situation where I need to prevent jQuery ready handlers from firing on the DOMContentReady event under certain conditions. These handlers are set up in different places like include files, plugins, and more. While one approach could involve s ...

Exploring the capabilities of nightmare for automating websites that employ ajax technologies

Currently, I am utilizing Nightmare to automate tasks on a website. While it has proven to be effective overall, I have encountered some challenges when trying to interact with dynamically loaded content. Nightmare offers a method called .wait(#elementId) ...

TypeScript version 3.7 has implemented a new feature where it will now display errors for each individual invalid prop instead of grouping them together as it

Scenario using TypeScript 3.5.3 https://i.stack.imgur.com/wykd6.png link to interactive playground - TS 3.5.3 demo running successfully Example with TypeScript 3.7.2 https://i.stack.imgur.com/BPckB.png link to demo - TS 3.7.2 demo not functioning correctl ...

The new update of React Native version 0.64.0 is facing issues with updating the bundle in iOS devices

Can anyone lend a hand with React Native? I've hit a roadblock since updating to RN 0.64.0. Everything seems to be working fine, except for the hot reload feature. RN doesn't seem to recognize changes, even though the Metro bundler starts up suc ...