官术网_书友最值得收藏!

Trailing commas in function arguments

Trailing commas are commas that are used after the final argument of a function. Using a comma after the last parameter of a function can be useful because it is very common to forget a comma when we modify an existing function by adding additional parameters.

For example, the following function only takes one parameter and doesn't use trailing commas:

function greetWithoutTralingCommas(
name: string
): string {
return 'Hi! ${name}';
}

Some time after the initial implementation, we might be required to add a parameter to the previous function. A common mistake is to declare the new parameter and forget to add a comma after the first parameter:

function updatedGreetWithoutTralingCommas(
name: string
surname: string, // Error
): string {
return 'Hi! ${name} ${surname}';
}

Using a trailing comma in the first version of the function could have helped us to prevent this common mistake:

function greetWithTralingCommas(
name: string,
): string {
return 'Hi! ${name}';
}

Using a trailing comma eliminates the possibility of forgetting the comma when adding a new argument:

function updatedGreetWithTralingCommas(
name: string,
surname: string,
): string {
return 'Hi! ${name} ${surname}';
}
TypeScript will throw an error if we forget a comma, so trailing commas are not needed as much as they are when working with JavaScript. Trailing commas are optional, but using them is considered good practice by many JavaScript and TypeScript engineers.
主站蜘蛛池模板: 兴山县| 鸡东县| 论坛| 城步| 巴楚县| 河北区| 普格县| 西华县| 明水县| 平乡县| 张掖市| 蕲春县| 略阳县| 邹城市| 监利县| 偏关县| 淮滨县| 七台河市| 南川市| 宝应县| 禄丰县| 黑龙江省| 柳州市| 十堰市| 镇原县| 白山市| 东阿县| 牟定县| 黎川县| 灵台县| 岚皋县| 东乡族自治县| 庆安县| 青浦区| 阿城市| 尚义县| 冀州市| 花莲市| 乐亭县| 长丰县| 铜山县|