函数类型

Function Type

为函数定义类型

Define types for functions

我们可以给每个参数添加类型之后再为函数本身添加返回值类型。 TypeScript能够根据返回语句自动推断出返回值类型,因此我们通常省略它。

We can add a type to each parameter and then a return value type to the function itself. TypeScript can automatically infer the return

value type from the return statement, so we usually omit it.

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

书写完整函数类型

Write complete function type

let myAdd:(x:number,y:number)=>number=
function(x:number,y:number):number{return x+y;};

函数类型包含两部分:参数类型和返回值类型。 当写出完整函数类型的时候,这两部分都是需要的。

Function types consist of two parts: parameter type and return value type. These two parts are needed when writing out the complete function type.

我们以参数列表的形式写出参数类型,为每个参数指定一个名字和类型。 这个名字只是为了增加可读性。

We write parameter types in the form of parameter lists, specifying a name and type for each parameter. The name is just for readability.

let myAdd:(baseValue:number,increment:number)=>number=

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

只要参数类型是匹配的,那么就认为它是有效的函数类型,而不在乎参数名是否正确。

As long as the parameter type matches, it is considered a valid function type, regardless of whether

the parameter name is correct or not.

第二部分是返回值类型。 对于返回值,我们在函数和返回值类型之前使用( =>)符号,使之清晰明了。 如之前提到的,

The second part is the type of return value. For return values, we use (=>) symbols before functions and return

value types to make them clear. As mentioned earlier,

返回值类型是函数类型的必要部分,如果函数没有返回任何值,你也必须指定返回值类型为 void而不能留空。

The return value type is a necessary part of the function type. If the function does not return any value, you

must also specify the return value type as void instead of leaving it blank.

函数的类型只是由参数类型和返回值组成的。 函数中使用的捕获变量不会体现在类型里。 实际上,这些变量是函数的隐藏状态并不是组成API的一部分。

The type of function consists of only the parameter type and the return value. Capture variables used in functions are not reflected in types.

In fact, these variables are hidden states of functions and are not part of the API.

推断类型

Inference type

let myAdd=function(x:number,y:number):number{return x+y};
let myAdd:(baseValue:number,increment:number)=>number=
function(x,y){return x+y;};

可选参数和默认参数

Optional and default parameters

传递给一个函数的参数个数必须与函数期望的参数个数一致。

The number of parameters passed to a function must be the same as the number of parameters expected by the function.

function buildName(firstName:string,lastName:string){
return firstName+""+lastName;
}
let result1=buildName("Bob");//error
let result2=buildName("Bob","Adams","Sr.");//error to many
let result3=buildName("Bob","Adams");//right

JavaScript里,每个参数都是可选的,可传可不传。 没传参的时候,它的值就是undefined。

In JavaScript, each parameter is optional and passable. When no parameter is passed, its value is undefined.

在TypeScript里我们可以在参数名旁使用 ?实现可选参数的功能。

In TypeScript, we can use it next to the parameter name to realize the function of optional parameters.

function buildName(firstName:string,lastName?:string){
if(lastName){
return firstName+""+lastName;
}else{
return firstName;
}
}
let result1=buildName("Bob");//right
let result2=buildName("Bob","Adams","Sr.");//error to many
let result3=buildName("Bob","Adams");//right

可选参数必须跟在必须参数后面。 如果上例我们想让first name是可选的,那么就必须调整它们的位置,把first name放在后面。

Optional parameters must follow the required parameters. If we want the first name to be optional in the previous example,

we have to adjust their position and put the first name at the back.

在TypeScript里,我们也可以为参数提供一个默认值当用户没有传递这个参数或传递的值是undefined时。 它们叫做有默认初始化值的参数。

In TypeScript, we can also provide a default value for a parameter when the user does not pass the parameter or the passed value

is undefined. They are called parameters with default initialization values.

function buildName(firstName:string,lastName="Smith"){
return firstName+""+lastName;
}
let result1=buildName("Bob");//right
let result1=buildName("Bob",undefined);//right
let result2=buildName("Bob","Adams","Sr.");//error to many
let result3=buildName("Bob","Adams");//right

与普通可选参数不同的是,带默认值的参数不需要放在必须参数的后面。 如果带默认值的参数出现在必须参数前面,

用户必须明确的传入 undefined值来获得默认值。

Unlike ordinary optional parameters, parameters with default values do not need to be placed after the required parameters.

If a parameter with a default value appears before the required parameter, the user must explicitly pass in the undefined value to get the default value.

function buildName(firstName="Will",lastName:string){
return firstName+""+lastName;
}
let result1=buildName("Bob");//error
let result2=buildName("Bob","Adams","Sr.");//error to many
let result3=buildName("Bob","Adams");//right
let result4=buildName(undefined,"Adams");//right

剩余参数

Residual parameters

必要参数,默认参数和可选参数有个共同点:它们表示某一个参数。 有时,你想同时操作多个参数,或者你并不知道会有多少参数传递进来。

在JavaScript里,你可以使用 arguments来访问所有传入的参数。

Necessary parameters, default parameters and optional parameters have one thing in common: they represent a parameter.

Sometimes, you want to operate on multiple parameters at the same time, or you don't know how many parameters will be passed in.

In JavaScript, you can use arguments to access all incoming parameters.

在TypeScript里,你可以把所有参数收集到一个变量里:

In TypeScript, you can collect all the parameters into one variable:

function buildName(firstName:string,...restOfName:string[]){
return firstName+""+restOfName.join("");
}
let employeeName=buildName("Joseph","Samuel","Lucas","MacKinzie");

剩余参数会被当做个数不限的可选参数。 可以一个都没有,同样也可以有任意个。 编译器创建参数数组,

名字是你在省略号( ...)后面给定的名字,你可以在函数体内使用这个数组。

The remaining parameters are treated as an unlimited number of optional parameters. You can have none,

you can have any. The compiler creates an array of parameters with the name you give after the ellipsis (...),

which you can use in the body of the function.

这个省略号也会在带有剩余参数的函数类型定义上使用到:

This ellipsis is also used in the definition of function types with residual parameters:

function buildName(firstName:string,...restOfName:string[]){
return firstName+""+restOfName.join("");
}
let buildNameFun:(fname:string,..rest:string[])=>string=buildName;

关于this

About this

interface Card{
suit:string;
card:number;
}
interface Deck{
suits:string[];
cards:number[];
createCardPicker(this:Deck):()=>Card;
}
let deck:Deck={
suits: ["hearts", "spades", "clubs", "diamonds"],
cards:Array(52),
createCardPicker:function(this:Deck){
return ()=>{
let pickedCard=Math.floor(Math.random()*52);
let pickedSuit=Math.floor(pickedCard/13);
return {suit:this.suits[pickedSuit],card:pickedCard%13};
}
}
}
let cardPicker=deck.createCardPicker();
let pickedCard=cardPicker();
alert("card:"+pickedCard.card+"of"+pickedCard.suit);

this参数在回调函数里

This parameter is in the callback function

函数的作者要指定 this的类型

The author of the function specifies the type of this

interface UIElement{
addClickListener(onclick:(this:void,e:Event)=>void):void;
}
class Handler{
info:string;
onClickBad(this:Handler,e:Event){
this.info=e.message;
}
}
let h=new Handler();
uiElement.addClickListener(h.onClickBad);//error!
class Handler{
info:string;
onClickBad(this:Handler,e:Event){
this.info=e.message;
}
}
var h=new Handler();
uiElement.addClickListener(h.onClickBad);//error!
class Handler{
info:string;
onClickGood(this:void,e:Event){
console.log('clicked!');
}
}
let h=new Handler();
uiElement.addClickListener(h.onClickGood);
class Handler{
info:string;
onClickGood:(e:Event)=>{this.info=e.message}
}

重载

heavy load

JavaScript本身是个动态语言。 JavaScript里函数根据传入不同的参数而返回不同类型的数据是很常见的。

JavaScript itself is a dynamic language. It is common for functions in JavaScript to return different types

of data depending on the parameters passed in.

let suits = ["hearts", "spades", "clubs", "diamonds"];
function pickedCard(x):any{
if(typeof x=="obj"){
let pickedCard=Math.floor(Math.random()*x.length);
return pickedCard;
}else if(typeof x=="number"){
let pickedSuit=Math.floor(x/13);
return {suit:suits[pickedSuit],card:x%13};
}
}
let myDeck = [{ suit: "diamonds", card: 2 }, { suit: "spades", card: 10 }, { suit: "hearts", card: 4 }];
let pickedCard1=myDeck[pickedCard(myDeck)];
let pickedCard1=myDeck[pickedCard(myDeck)];
alert("card: " + pickedCard1.card + " of " + pickedCard1.suit);
let pickedCard2 = pickCard(15);
alert("card: " + pickedCard2.card + " of " + pickedCard2.suit);

方法是为同一个函数提供多个函数类型定义来进行函数重载。

The method is to provide multiple function type definitions for the same function for function overloading.

let suits = ["hearts", "spades", "clubs", "diamonds"];
function pickCard(x: {suit: string; card: number; }[]): number;
function pickCard(x: number): {suit: string; card: number; };
function pickCard(x):any{
if (typeof x == "object") {
let pickedCard = Math.floor(Math.random() * x.length);
return pickedCard;
}
else if (typeof x == "number") {
let pickedSuit = Math.floor(x / 13);
return { suit: suits[pickedSuit], card: x % 13 };
}
}
let myDeck = [{ suit: "diamonds", card: 2 }, { suit: "spades", card: 10 }, { suit: "hearts", card: 4 }];
let pickedCard1 = myDeck[pickCard(myDeck)];
alert("card: " + pickedCard1.card + " of " + pickedCard1.suit); let pickedCard2 = pickCard(15);
alert("card: " + pickedCard2.card + " of " + pickedCard2.suit);

typescript函数(笔记非干货)的更多相关文章

  1. typescript枚举,类型推论,类型兼容性,高级类型,Symbols(学习笔记非干货)

    枚举部分 Enumeration part 使用枚举我们可以定义一些有名字的数字常量. 枚举通过 enum关键字来定义. Using enumerations, we can define some ...

  2. typescript基础类型(学习笔记非干货)

    布尔值 Boolean let isDone:boolean=false; 数字 Number let decLiteral:number=6; let hexLiteral:number=0xf00 ...

  3. typescript泛型(学习笔记非干货)

    软件工程中,我们不仅要创建一致的定义良好的API,同时也要考虑可重用性. 组件不仅能够支持当前的数据类型,同时也能支持未来的数据类型, 这在创建大型系统时为你提供了十分灵活的功能. In softwa ...

  4. typescript类(学习笔记非干货)

    我们声明一个 Greeter类.这个类有3个成员:一个叫做greeting的属性,一个构造函数和一个greet方法. We declare a Greeter class. This class ha ...

  5. typescript接口(学习笔记非干货)

    typescript的核心原则之一就是对所具有的shape类型检查结构性子类型化 One of the core principles of typescript is to check struct ...

  6. typescript变量声明(学习笔记非干货)

    var a=10; function f(){ var message="hello,world"; return message; } function f(){ a=10; r ...

  7. Typescript 学习笔记三:函数

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  8. mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)

    最后更新时间:2017-07-13 11:10:49 原始文章链接:http://www.lovebxm.com/2017/07/13/mongodb_primer/ MongoDB - 简介 官网: ...

  9. Typescript 学习笔记二:数据类型

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

随机推荐

  1. linux下syslog-ng日志集中管理服务部署记录

    syslog是Linux系统默认的日志守护进程,默认的syslog配置文件是/etc/syslog.conf文件.syslog守护进程是可配置的,它允许人们为每一种类型的系统信息精确地指定一个存放地点 ...

  2. github作业

    链接:   https://github.com/liuyu13/liuyu13-1 总结:git可以学习的东西还有很多.git协议,分布式协作,git项目管理,git技巧,github的使用和实践, ...

  3. shell之重定向

    使用>和>>都表示向结果重定向到一个文件中,区别在于>是覆盖式的重定向,会先将内容先清空,然后再将结果输入,而>>是追加式的重定向,是将要输入的内容追加在在已存在的 ...

  4. PAT L2-011 玩转二叉树

    https://pintia.cn/problem-sets/994805046380707840/problems/994805065406070784 给定一棵二叉树的中序遍历和前序遍历,请你先将 ...

  5. HDU 2012 素数判定

    http://acm.hdu.edu.cn/showproblem.php?pid=2012 Problem Description 对于表达式n^2+n+41,当n在(x,y)范围内取整数值时(包括 ...

  6. webstrom 安装Babel

    https://www.jianshu.com/p/b9bd2ec9ec80 https://www.cnblogs.com/zhishaofei/p/6061568.html https://blo ...

  7. Idea解决打开大文件消耗CPU问题

    dea打开大文件的时候,会导致cpu利用率变得特别高,我这边八核i7的配置下,cpu依然飙到了600%~700%,这个时候就需要修改idea的配置(下面以Ubuntu为例). 1.进入到idea安装目 ...

  8. 如何判断一条记录什么字段被修改了 [问题点数:40分,结帖人bluesukeke]

    查询出来数据,在数据集编辑状态下,如何判断一条记录被修改了,哪些字段被修改了. 可用adoquery的Delta屬性...eg: ClientDataSet1.Delta... PS:POST前是準確 ...

  9. wordpress文章页两侧添加分页导航箭头

    分页导航 如果添加在文章页的两侧,很方便读者翻阅,小编发现好多站长的博客都添加了这一功能,百度了一下,就是JS和css的功能,经过测试成功,分享一下流程. 1.添加Js 在headr.php或者foo ...

  10. Codeforces Round #394 (Div. 2) C. Dasha and Password

    C. Dasha and Password time limit per test 2 seconds memory limit per test 256 megabytes input standa ...