使用解构如何在具有默认自定义类型的函数中接收参数

Using destructuring how to receive parameters in a function with a default custom type

我创建了一个服务来使用 Mat-snackbar 发出警报,我使用解构来接收我的函数中的变量,我要求其中一个变量是特定类型

export class NotificationsService {

  // MatSnackBarVerticalPosition = 'top' | 'bottom'; this is the required type

  constructor(private snackBar: MatSnackBar) {
  }

  alert({ message, buttonText = 'Ok', verticalPosition = 'top' }) {
    let alertConfig = {
      verticalPosition: verticalPosition,
    };
    this.snackBar.open(message, buttonText, alertConfig);
  }
}

verticalPosition属性是MatSnackBarVerticalPosition类型(可以是'bottom'或者'top'),我不知道怎么设置默认的top或者bottom的值,因为它告诉我有一个错误,因为无法将字符串类型转换为 MatSnackBarVerticalPosition

这个解决方案对我有用,将默认值分配给另一个具有所需类型的变量

verticalPosition: MatSnackBarVerticalPosition = 'top';

alert({ message, buttonText = 'Ok', verticalPosition = this.verticalPosition }) {
    let alertConfig = {
      verticalPosition: verticalPosition,
    };
    this.snackBar.open(message, buttonText, alertConfig);
  }

因此,您希望实现以下目标:

let a = {
    aa: 123,
    bb:456,
    cc
};

const {aa, bb, cc = 'Top'}: {aa: number, bb: number, cc: string} = a;

console.log(cc); // Will log 'Top'

我想你的情况可能是这样的:

interface yourType {
  message: string,
  buttonText: string,
  verticalPosition: MatSnackBarVerticalPosition
}

alert({ message, buttonText = 'Ok', verticalPosition = 'top' }: yourType) {
    let alertConfig = {
      verticalPosition: verticalPosition,
    };
    this.snackBar.open(message, buttonText, alertConfig);
  }
  

你能试试这个吗? :)

Reference

这是关于打字。您需要 declare/assert 在某处键入以使 TypeScript 满意,例如:

const alertConfig = {
    verticalPosition: verticalPosition as MatSnackBarVerticalPosition,
};