Angular Material - 类型 'string' 不可分配给类型 'MatSnackBarHorizontalPosition'

Angular Material - Type 'string' is not assignable to type 'MatSnackBarHorizontalPosition'

我创建了一个使用 material snackbar 显示消息的函数。

showMessage(message: string, position = { horizontal: "right", vertical: "bottom" }): void {
    const _htmlMessage ="some message";
    this.snackBar.openFromComponent(SnackbarComponent, {
        data: {
            html: _htmlMessage
        },
        duration: 2000,
        horizontalPosition: position.horizontal,
        verticalPosition: position.vertical
    });
}

但这表明:

Type 'string' is not assignable to type 'MatSnackBarHorizontalPosition'.ts(2322)

snack-bar-config.d.ts(42, 5): The expected type comes from property 'horizontalPosition' which is declared here on type 'MatSnackBarConfig'

但是如果我直接这样赋值:

duration: 2000,
horizontalPosition: "right",
verticalPosition: "bottom"

这行得通。我该如何解决?

解决方案 1:为 position.

定义类型
import {
  MatSnackBarHorizontalPosition,
  MatSnackBarVerticalPosition
} from '@angular/material/snack-bar';

showMessage(
    message: string,
    position: {
      horizontal: MatSnackBarHorizontalPosition;
      vertical: MatSnackBarVerticalPosition;
    } = { horizontal: 'right', vertical: 'bottom' }
  ): void {
    const _htmlMessage = 'some message';
    this._snackBar.openFromComponent(SnackbarComponent, {
      data: {
        html: _htmlMessage
      },
      duration: 2000,
      horizontalPosition: position.horizontal,
      verticalPosition: position.vertical
    });
}

Sample Solution 1 on StackBlitz


解决方案 2:将 horizontalvertical 都转换为各自的类型。

import {
  MatSnackBarHorizontalPosition,
  MatSnackBarVerticalPosition
} from '@angular/material/snack-bar';

showMessage(
    message: string,
    position = { horizontal: 'right', vertical: 'bottom' }
  ): void {
    const _htmlMessage = 'some message';
    this._snackBar.openFromComponent(SnackBarOverviewExample, {
      data: {
        html: _htmlMessage
      },
      duration: 2000,
      horizontalPosition: position.horizontal as MatSnackBarHorizontalPosition,
      verticalPosition: position.vertical as MatSnackBarVerticalPosition
    });
  }
}

Sample Solution 2 on StackBlitz


参考资料

MatSnackBarHorizontalPosition & MatSnackBarVerticalPosition (Type aliases)