Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

javascript - open-ended function arguments with TypeScript

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:

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

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

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#?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

This will then type check correctly with

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...