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

Angular 使用解构如何在具有默认自定义类型的函数中接收参数,angular,typescript,angular-material,destructuring,Angular,Typescript,Angular Material,Destructuring,我已经创建了一个使用Mat snackbar发出警报的服务,我使用destructuring来接收函数中的变量,我要求其中一个变量为特定类型 export class NotificationsService { // MatSnackBarVerticalPosition = 'top' | 'bottom'; this is the required type constructor(private snackBar: MatSnackBar) { } alert({

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

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);
  }

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

verticalPosition: MatSnackBarVerticalPosition = 'top';

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

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

a={
机管局:123,
bb:456,
复写的副本
};
常量{aa,bb,cc='Top'}:{aa:number,bb:number,cc:string}=a;

console.log(cc);//将记录“Top”
,因此请注意,您希望实现以下目标:

a={
机管局:123,
bb:456,
复写的副本
};
常量{aa,bb,cc='Top'}:{aa:number,bb:number,cc:string}=a;

console.log(cc);//将记录“Top”
这是关于键入的。您需要在某个地方声明/断言类型以使TypeScript满意,例如:

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

是关于打字的。您需要在某个地方声明/断言类型以使TypeScript满意,例如:

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

我希望在函数中接收具有特定类型的属性,而不是声明它。我希望在函数中接收具有特定类型的属性,而不是声明它。