繁体   English   中英

如何为 TypeScript 的“类型别名”类型使用常量值?

[英]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.

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