如何为 TypeScript 'Type Aliases' 类型使用常量值?

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

我是 TypeScript 的新手。

在一个 Angular 项目中,我正在准备一个 SnackBar 服务以通知用户。

我有一些 Java 背景。

我有两个问题。

在 TypeScript 中定义 class 我不能使用 "const" 关键字。我的服务将是一个单例,所以如果它在某个地方意外地改变了我的价值,我的整个应用程序都会崩溃。因此,我尝试了私人领域。但是我觉得还不够。

1) TypeScript 可以为 class 字段提供类似 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) 由于 'Type Aliases' 我的代码没有编译。我如何使用 'Type Aliases' 的 const 值?

以上 class 未编译,消息为:

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';