简体   繁体   English

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

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

I am new in TypeScript.我是 TypeScript 的新手。

On an Angular Project, I am preparing a SnackBar Service in order to notify user.在 Angular 项目中,我正在准备 SnackBar 服务以通知用户。

I have some Java background.我有一些 Java 背景。

I have two question.我有两个问题。

In TypeScript while defining a class I can not use "const" keyword.在定义类时,在 TypeScript 中我不能使用“const”关键字。 And my service going to be a singleton so if it changes the my value accidently in somewhere my whole application gonna break.我的服务将是一个单例,所以如果它在某个地方意外地改变了我的价值,我的整个应用程序都会崩溃。 Because of that I tried private field.因此,我尝试了私人领域。 But I think it is not enough.但我认为这还不够。

1) TypeScript can provide us someting like const for a class field? 1) TypeScript 可以为类字段提供类似 const 的东西吗?

In my service:在我的服务中:

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) Because of 'Type Aliases' my code is not compiling. 2) 由于“类型别名”,我的代码没有编译。 How could I use const values for 'Type Aliases'?我如何为“类型别名”使用 const 值?

Above class is not compiling and message is:上面的类没有编译,消息是:

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.

But in 'MatSnackBarConfig', 'MatSnackBarHorizontalPosition ' already a string.但是在“MatSnackBarConfig”中,“MatSnackBarHorizontalPosition”已经是一个字符串。

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

Your problem is with string literal types not type aliases.您的问题是字符串文字类型而不是类型别名。 A string literal type is a subtype of string so you can assign the type 'end' to a string but not the other way around.字符串文字类型是string的子类型,因此您可以将类型'end'分配给字符串,但反之则不行。

You can make the compiler infer a string literal type for a field if it is readonly如果字段是只读的,您可以让编译器推断字段的字符串文字类型

private readonly HORIZANTAL_POSITION = 'end';

If the field is not readonly you can manually specify the type如果该字段不是只读的,您可以手动指定类型

private HORIZANTAL_POSITION : MatSnackBarHorizontalPosition = 'end';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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