What is the syntax for declaring a variable with multiple types in Angular/Typescript?

Imagine having a variable declared with the following type:

test?: boolean | { [key in TestEnum ]: boolean };

Now, let's assign this test variable within a constant where it can hold either a boolean value or a mapping to an enum. Consider the example below:

EXAMPLE OF SETTING VALUES IN A CONSTANT OBJECT

export const TEST_1 {
  name: "Mark",
  test: {
    [TestEnum.Value1]: false,
    [TestEnum.Value2]: true,
    [TestEnum.Value3]: true,
    [TestEnum.Value4]: true
  }

  }
};

export const TEST_2 {
  name: "Mark",
  test: true
  }
};

How would one access this test variable in their component when it could be simply test or test[TestEnum.Value2]?

Answer №1

As mentioned in the official handbook, TypeScript allows for type narrowing using the typeof operator. In your scenario, you can specifically check whether a value is a boolean or an object:

export interface MyInterface {
    name: string;
    test?: boolean | { [key in TestEnum ]: boolean };
}

export const TEST_1: MyInterface = {
  name: "Mark",
  test: {
    [TestEnum.Value1]: false,
    [TestEnum.Value2]: true,
    [TestEnum.Value3]: true,
    [TestEnum.Value4]: true
  }
};

export const TEST_2: MyInterface = {
  name: "Mark",
  test: true
};

function process(value: MyInterface) {
    if (typeof value.test === 'boolean') {
        console.log(value.test) // This is a boolean value;
    } else if (typeof value.test === 'object') {
        console.log(value.test[TestEnum.Value2]); // Since it's an object, we can access its properties
    }
}

You can also explore this interactive TypeScript playground demo, where I attempted to access test[TestEnum.Value2] outside the typeof guard and encountered an error.

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

Set theme value for the tab group in Angular Material

Trying to change the tab theme in Angular Material by setting it directly seems to be a bit tricky. The example from Angular Material shows how to do it with a toggle button, but when I try to code it directly, it doesn't work. Here's the code sn ...

Adding 30 Days to a Date in Typescript

Discovering Typescript for the first time, I'm attempting to calculate a date that is (X) months or days from now and format it as newDate below... When trying to add one month: const dateObj = new Date(); const month = dateObj.getUTCMonth() + 2; con ...

Modify the data displayed on the chart by choosing the desired year from the dropdown options

In my Angular app, I am showcasing a chart that visualizes data based on selected starting and ending years from dropdown menus. The X axis represents 18 cities, while the Y axis displays "IAP" values. To calculate the "IAP" values for each city within the ...

Are you encountering issues with Google Analytics performance on your Aurelia TypeScript project?

I recently started using Google Analytics and I am looking to integrate it into a website that I'm currently building. Current scenario Initially, I added the Google Analytics tracking code to my index.ejs file. Here is how the code looks: <!DOC ...

Error message: Invalid form submission in Django REST framework

I am currently working with a model, model form and view structured in the following way: @api_view(['POST']) def addCigar(request): print(request.POST) form = CigarForm() if request.POST: form = CigarForm(request.POST) ...

Showing and hiding nested Form Group validation in Angular 4 is a crucial feature that can improve

I have been exploring Angular 4 validation recently. Currently, I am working with a reactive form that contains two radio buttons and two form groups. The behavior I'm trying to achieve is when the user selects the first radio button, it removes valid ...

Having trouble running Angular CLI in Git Bash terminal on Windows?

I have been attempting to set up the Angular CLI using npm. Currently, my node version is v11.2.0 and my npm version is 6.4.1. Upon executing the command npm install -g @angular/cli, the output I receive is as follows: C:\Users\Mark O'Hare ...

Return the previous value if the filter function returns false in RxJs

In an attempt to optimize performance and reduce unnecessary requests to the server, this code checks if values exist in the store before making additional requests. While the overall logic functions correctly, there is an issue where if the filter returns ...

Disabling a button until a selection is made in a combobox using Angular

I am currently working on a template that includes a combobox, a button, and a table. What I am trying to achieve is to make the buttons unclickable unless a value is selected from the combobox. After selecting a value, the button will call a service metho ...

Receiving an Error 404 "not found" when making a Node.js POST Request using an Angular application

I have been working on developing an API with Node.js that connects to an SQL Server database. While my GET requests are functioning properly, I am encountering errors with my POST request. To organize my node project, I have split it into two files - a ro ...

Angular HTTP Interceptor encountering issue with TypeError: (0 , x.fromPromise) function is not recognized

I have implemented the following code snippet to attach reCAPTCHA v3 to an HTTP Request: @Injectable() export class RecaptchaInterceptor implements HttpInterceptor { constructor(private recaptchaService: ReCaptchaService) { } intercept(httpRequest: HttpRe ...

Tips for setting a default value in a Reactive Form

How can I transfer a default value from HTML to TypeScript using reactive forms? <ul class="list list_2"> <li>Subtotal <span>{{cartTotal | currency:'INR':true:'2.0'}}</span></li> <li>Shippin ...

Cannon-js: Experience dynamic body bouncing on the y axis as it reacts to force applied on the x and z axes

Currently, I am working on an FPS game where the player controller applies force based on keyboard inputs to a dynamic cannon body. The angular dampening is set to 1 on the player body. The PlayerController class takes both the player class (which extends ...

How can variables from state be imported into a TypeScript file?

Utilizing vue.js along with vuetify, I have a boolean value stored in state via Vuex defined in src/store/index.ts (named darkMode). This value is used within one of my view components inside a .vue file. However, I now wish to access the same variable in ...

How to access the types of parameters in a function type

I am working on a function that takes a value and default value as arguments. If the value is a boolean, I want the return type to match the type of the default value. Here is the function I have: export type DetermineStyledValue<T> = ( value: str ...

Is it possible for component tags that are generated to be altered?

I am tasked with converting HTML/CSS documents to be compatible with Angular/cli. The CSS file uses single selectors like "section > section > div", but the generated HTML contains non-standard "component tags" that break these selectors. Instead o ...

Discovering nested trees within a tree structure in typescript

Imagine having a tree structure in JavaScript like this: a1 --b ----c1 a2 --b2 --b3 ----c2 If you needed to find c2, the path would be a2->b3->c2 Now, consider the following JSON object representing a family tree: treeFamily = { name ...

Pull in class definitions from the index.js file within the node_modules directory

In my project, I have the package called "diagram-js" in the node_modules. The file node_modules/diagram-js/lib/model/index.js contains multiple class definitions as shown below: /** * @namespace djs.model */ /** * @memberOf djs.model */ /** * The b ...

Guide to testing error throwing in error events with Jest

I am having an issue with a particular learning case. The code snippet below is what I am dealing with and I aim to test error throwing: export const someFunction = async () => { //... const fileReadStream = createReadStream(absoluteFilePath) .on(&a ...

Advantages of optimizing NodeJS/TypeScript application by bundling it with webpack

Currently, I am working on a Node/Express application and I am interested in incorporating the most recent technologies. This includes using TypeScript with node/Express along with webpack. I have a question: What advantages come with utilizing webpack t ...