I am an Angular Developer and working on one project in which I used strict DataType and define variable with my custom DataType Like this :
Code: 1 | 2 | 3 | 4 | 5 = 1;
Here above variable declaration will work perfect if we assign this code
variable with constant value directly. like this :
Code = 3;
But this will give an Error if I try to assign it using a variable like this :
let num = this.getNumberBewteen1_5();
Code = num;
and function getNumberBewteen1_5()
is the function which return one number between 1 and 5 ;
Is there any way to fix it without remove strict DataType
in angular ?
The problem is that method returned type should be the same as variable type.
You try to assign number to 1 | 2 | 3 | 4 | 5 which is different type.
Working example:
import { Component } from '@angular/core';
type YourType = 1 | 2 | 3;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
a: YourType;
constructor() {
let b = this.yourMethod();
this.a = b;
}
yourMethod(): YourType { // returned type is YourType (not number)
return 1; // or 2 | 3
}
}