简体   繁体   中英

How to use constant values for TypeScript 'Type Aliases' types?

I am new in TypeScript.

On an Angular Project, I am preparing a SnackBar Service in order to notify user.

I have some Java background.

I have two question.

In TypeScript while defining a class I can not use "const" keyword. And my service going to be a singleton so if it changes the my value accidently in somewhere my whole application gonna break. Because of that I tried private field. But I think it is not enough.

1) TypeScript can provide us someting like const for a class field?

In my service:

import {Injectable} from '@angular/core';
import {MatSnackBar} from '@angular/material';

@Injectable({
  providedIn: 'root'
})
export class SnackService {

  private DURATION = 1800;

  private HORIZANTAL_POSITION = 'end';

  constructor(private sncackBar: MatSnackBar) {

  }

  successful(message: string) {
    this.sncackBar.open(message, null, {
      duration: this.DURATION,
      horizontalPosition: this.HORIZANTAL_POSITION,
      panelClass: 'success-snackBar'
    });
  }

  error(message: string) {
    this.sncackBar.open(message, null, {
      duration: this.DURATION,
      horizontalPosition: this.HORIZANTAL_POSITION,
      panelClass: 'error-snackBar'
    });
  }
}

2) Because of 'Type Aliases' my code is not compiling. How could I use const values for 'Type Aliases'?

Above class is not compiling and message is:

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.

But in 'MatSnackBarConfig', 'MatSnackBarHorizontalPosition ' already a string.

export declare type MatSnackBarHorizontalPosition = 'start' | 'center' | 'end' | 'left' | 'right';

Your problem is with string literal types not type aliases. A string literal type is a subtype of string so you can assign the type 'end' to a string but not the other way around.

You can make the compiler infer a string literal type for a field if it is readonly

private readonly HORIZANTAL_POSITION = 'end';

If the field is not readonly you can manually specify the type

private HORIZANTAL_POSITION : MatSnackBarHorizontalPosition = 'end';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM