使用 TypeScript 的开放式函数参数 [英] open-ended function arguments with TypeScript

查看:41
本文介绍了使用 TypeScript 的开放式函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IMO,TypeScript 语言的主要关注点之一是支持现有的 vanilla JavaScript 代码.这是我第一眼的印象.看看下面这个完全有效的 JavaScript 函数:

IMO, one of the main concerns of the TypeScript language is to support the existing vanilla JavaScript code. This is the impression I had at first glance. Take a look at the following JavaScript function which is perfectly valid:

注意:我并不是说我喜欢这种方法.我只是说这是一个有效的 JavaScript 代码.

Note: I am not saying that I like this approach. I am just saying this is a valid JavaScript code.

function sum(numbers) { 

    var agregatedNumber = 0; 
    for(var i = 0; i < arguments.length; i++) { 
        agregatedNumber += arguments[i];
    }

    return agregatedNumber;
}

所以,我们使用任意数量的参数来使用这个函数:

So, we consume this function with any number of arguments:

console.log(sum(1, 5, 10, 15, 20));

但是,当我使用 TypeScript Playground 尝试此操作时,会出现编译时错误.

However, when I try this out with TypeScript Playground, it gives compile time errors.

我假设这是一个错误.假设我们没有兼容性问题.那么,有没有办法用开放式参数编写这种类型的函数?比如C#中的params特性?

I am assuming that this is a bug. Let's assume that we don't have the compatibility issues. Then, is there any way to write this type of functions with open-ended arguments? Such as params feature in C#?

推荐答案

TypeScript 的做法是在参数名称之前放置省略号运算符 (...).上面可以写成,

The TypeScript way of doing this is to place the ellipsis operator (...) before the name of the argument. The above would be written as,

function sum(...numbers: number[]) {
    var aggregateNumber = 0;
    for (var i = 0; i < numbers.length; i++)
        aggregateNumber += numbers[i];
    return aggregateNumber;
}

这将使用

console.log(sum(1, 5, 10, 15, 20));

这篇关于使用 TypeScript 的开放式函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆