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

Functions

Parameters and return values in the function signature can be typed too. Types protects you against JavaScript errors during function execution because the compiler warns you punctually at build time when the wrong types are used:

function add(x: number, y: number): number {
return x + y;
}

Function type is a way to declare the type of a function. To explicitly declare a function type, you should use the keywords var or let, a variable name, a colon, a parameter list, a fat arrow =>, and the function's return type:

var fetchName: (division: Division, customer: Customer) => string;

Now, you must provide an implementation of this declaration:

fetchName = function (division: Division, customer: Customer): string {
// do something
}

This technique is especially useful for callbacks. Imagine a filter function which filters arrays by some criterion. An exact criterion can be encapsulated in the passed in callback function that acts as predicate:

function filter(arr: number[], callback: (item: number) => boolean): number[] {
let result: number[] = [];
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i])) {
result.push(arr[i]);
}
}
return result;
}

A possible function call with a specific callback could appear as follows:

let result = filter([1, 2, 3, 4], (item: number) => item > 3);

In TypeScript, every function parameter is assumed to be required. There are two ways to mark a parameter as optional (optional parameters can be omitted when calling the function).

  • Use a question mark after the parameter name:
function doSomething(param1: string, param2?: string) {
// ...
}
  • Use the parameter's default value (ECMAScript 2015 feature), which gets applied when no value is provided:
function doSomething(param1: string, param2 = "some value") {
// ...
}

Now, you are able to call this function with just one value.

doSomething("just one value");
主站蜘蛛池模板: 陇西县| 中西区| 凉山| 涟水县| 青龙| 个旧市| 柘城县| 山西省| 万州区| 建昌县| 海口市| 延安市| 伊金霍洛旗| 彭阳县| 湘潭县| 白山市| 普格县| 辽阳市| 襄垣县| 新沂市| 万源市| 聂荣县| 新竹市| 克东县| 昆山市| 航空| 象山县| 连城县| 缙云县| 兴城市| 班戈县| 迁安市| 沙湾县| 三穗县| 得荣县| 景德镇市| 夏邑县| 兴隆县| 隆德县| 博爱县| 沿河|