I am a beginner in the world of TypeScript.
Currently, I am working on an Angular Project where I am developing a SnackBar Service to provide notifications to users.
Although my background is primarily in Java, I have encountered some challenges.
I have a couple of queries.
When defining a class in TypeScript, I noticed that I cannot use the "const" keyword for class fields. Since my service needs to be a singleton, I am concerned about accidentally changing values and breaking the entire application. I tried using private fields, but it doesn't seem to be sufficient.
1) Is there a way in TypeScript to have something similar to const for class fields?
In my service:
import {Injectable} from '@angular/core';
import {MatSnackBar} from '@angular/material';
@Injectable({
providedIn: 'root'
})
export class SnackService {
private DURATION = 1800;
private HORIZONTAL_POSITION = 'end';
constructor(private snackBar: MatSnackBar) {
}
successful(message: string) {
this.snackBar.open(message, null, {
duration: this.DURATION,
horizontalPosition: this.HORIZONTAL_POSITION,
panelClass: 'success-snackBar'
});
}
error(message: string) {
this.snackBar.open(message, null, {
duration: this.DURATION,
horizontalPosition: this.HORIZONTAL_POSITION,
panelClass: 'error-snackBar'
});
}
}
2) My code is not compiling due to 'Type Aliases'. How can I use const values for 'Type Aliases'?
The above class is experiencing compilation issues with the following error message:
error TS2345: Argument of type '{ duration: number; horizontalPosition: string; panelClass: string; }' is not assignable to parameter of type 'MatSnackBarConfig<any>'.
Types of property 'horizontalPosition' are incompatible.
However, in 'MatSnackBarConfig', 'MatSnackBarHorizontalPosition' is already defined as a string.
export declare type MatSnackBarHorizontalPosition = 'start' | 'center' | 'end' | 'left' | 'right';