【问题标题】:How to use constant values for TypeScript 'Type Aliases' types?如何为 TypeScript 'Type Aliases' 类型使用常量值?
【发布时间】:2018-12-25 02:15:52
【问题描述】:

我是 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”中,“MatSnackBarHorizo​​ntalPosition”已经是一个字符串了。

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

【问题讨论】:

  • 你可以简单地检查MatSnackBarConfig&lt;any&gt;实际上是什么,然后应该解决第二个问题
  • 您需要导入 MatSnackBarHorizo​​ntalPosition 并将此类型分配给您的私有 HORIZONTAL_POSITION 值
  • 你在 this.sncackBar 中有一个错字
  • 单例可以保存在静态类字段中,以后可以确保构造函数中没有单个实例已经实例化
  • 如果您将变量名大写,因为您希望它们是常量,您可以使用 readonly 修饰符

标签: angular typescript angular-material2


【解决方案1】:

您的问题在于字符串文字类型而不是类型别名。字符串文字类型是 string 的子类型,因此您可以将类型 'end' 分配给字符串,但不能反过来。

你可以让编译器推断它的字段的字符串文字类型是只读的

private readonly HORIZANTAL_POSITION = 'end';

如果该字段不是只读的,您可以手动指定类型

private HORIZANTAL_POSITION : MatSnackBarHorizontalPosition = 'end';

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2016-01-16
    • 2013-06-08
    • 2022-01-15
    • 1970-01-01
    • 2016-11-05
    • 2021-07-06
    • 1970-01-01
    • 2021-12-06
    相关资源
    最近更新 更多