代码之家  ›  专栏  ›  技术社区  ›  Muhammed Ozdogan

如何对类型脚本的“类型别名”类型使用常量值?

  •  1
  • Muhammed Ozdogan  · 技术社区  · 6 年前

    我是打字新手。

    在一个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)由于“类型别名”,我的代码没有编译。“类型别名”如何使用常量值?

    上面的类没有编译,消息是:

    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';
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Titian Cernicova-Dragomir    6 年前

    您的问题是字符串文字类型,而不是类型别名。字符串文本类型是 string 这样您就可以分配类型 'end' 一根绳子,但不是另一根。

    您可以使编译器推断其字段的字符串文字类型为只读

    private readonly HORIZANTAL_POSITION = 'end';
    

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

    private HORIZANTAL_POSITION : MatSnackBarHorizontalPosition = 'end';