首页 > 解决方案 > 打字稿返回空对象类型语法

问题描述

返回函数中'{}'的含义是什么,该打字稿语法如何解释为es7。

export const genericRetryStrategy = ({
  maxRetryAttempts = 3,
  scalingDuration = 1000,
  excludedStatusCodes = []
}: {
  maxRetryAttempts?: number,
  scalingDuration?: number,
  excludedStatusCodes?: number[]
} = {}) => (attempts: Observable<any>) => {
    //FUNCTION IMPLEMENTATION
};

标签: typescriptecmascript-6

解决方案


让我们分解一下。您的函数声明基本上具有以下结构:

export const myFunc = (<parameter>: <type> = <default>) => <implementation>;

<parameter>声明部分是一个解构模式,它提取 3 个特定属性并将这些属性值传递给您的函数体。每个属性都是可选的,并且在它的值undefined在参数中的情况下被赋予一个默认值。

<type>部分简单地声明了预期的参数类型,在这种情况下是一个包​​含三个属性的对象,所有这些属性都可能是可选的。

该部分指示如果提供或不提供<default>参数,将用什么值替换此参数。undefined这使您可以完全不带参数调用函数,即以下所有内容都是等效的:

genericRetryStrategy({ maxRetryAttempts: 3, scalingDuration: 1000, excludedStatusCodes: [] });
genericRetryStrategy({});  // use default property values
genericRetryStrategy();    // use default parameter value

希望这可以清除语法。要将其转换为 es7,您所要做的就是删除<type>声明的部分,如下所示:

export const genericRetryStrategy = ({
  maxRetryAttempts = 3,
  scalingDuration = 1000,
  excludedStatusCodes = []
} = {}) => (attempts) => {
    //FUNCTION IMPLEMENTATION
};

推荐阅读