Home > Blockchain >  How to make TypeScript literal types in Angular (narrow from string to specific strings)?
How to make TypeScript literal types in Angular (narrow from string to specific strings)?

Time:03-20

I made a set of radio buttons:

enter image description here

<mat-radio-group [(ngModel)]="learningMode" aria-label="Select an learning mode">
    <mat-radio-button value="videos">Videos
            <mat-icon>videocam</mat-icon>
    </mat-radio-button>
    <mat-radio-button value="vocabulary">Vocabulary
            <mat-icon>feed</mat-icon>
    </mat-radio-button>
    <mat-radio-button value="wordSearch">Word Search
            <mat-icon>search</mat-icon>
    </mat-radio-button>
</mat-radio-group>

It works just great if I set learningMode as a string.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {
  learningMode: string = 'videos';
}

The TypeScript Handbook says that I can narrow string to a Literal Type, i.e., three strings:

s: string, alignment: "left" | "right" | "center"

But this doesn't work:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {
   learningMode: string, learningModes: 'videos' | 'vocabulary' | 'wordSearch' = 'videos';
}

How do I narrow learningMode from any string to any of three strings?

CodePudding user response:

If i understand corectly. There is my aproach how to narrow learningMode.

export declare type LearningModes = 'videos' | 'vocabulary' | 'wordSearch';

and after that i would say

 learningNodes: LearningModes;

You cannot use = (equal) in declaring type. So there should be some method (function) to handle this logic. For example with if else statement.

 example(test: string){
   if (test === 'videos'){
      return 'wordSearch'
    }
  }

CodePudding user response:

The syntax that you're using for declaring is kind off wrong.

learningMode: 'videos' | 'vocabulary' | 'wordSearch' = 'videos';
//where videos will be default value
  • Related