[英]How to use constant values for TypeScript 'Type Aliases' types?
我是 TypeScript 的新手。
在 Angular 項目中,我正在准備 SnackBar 服務以通知用戶。
我有一些 Java 背景。
我有兩個問題。
在定義類時,在 TypeScript 中我不能使用“const”關鍵字。 我的服務將是一個單例,所以如果它在某個地方意外地改變了我的價值,我的整個應用程序都會崩潰。 因此,我嘗試了私人領域。 但我認為這還不夠。
1) TypeScript 可以為類字段提供類似 const 的東西嗎?
在我的服務中:
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) 由於“類型別名”,我的代碼沒有編譯。 我如何為“類型別名”使用 const 值?
上面的類沒有編譯,消息是:
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.
但是在“MatSnackBarConfig”中,“MatSnackBarHorizontalPosition”已經是一個字符串。
export declare type MatSnackBarHorizontalPosition = 'start' | 'center' | 'end' | 'left' | 'right';
您的問題是字符串文字類型而不是類型別名。 字符串文字類型是string
的子類型,因此您可以將類型'end'
分配給字符串,但反之則不行。
如果字段是只讀的,您可以讓編譯器推斷字段的字符串文字類型
private readonly HORIZANTAL_POSITION = 'end';
如果該字段不是只讀的,您可以手動指定類型
private HORIZANTAL_POSITION : MatSnackBarHorizontalPosition = 'end';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.