函数类型

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. MySQL高可用方案-PXC环境部署记录

    之前梳理了Mysql+Keepalived双主热备高可用操作记录,对于mysql高可用方案,经常用到的的主要有下面三种: 一.基于主从复制的高可用方案:双节点主从 + keepalived 一般来说, ...

  2. centos7编译安装zabbix(附带编译安装lnmp)

    先把防火墙和selinux关闭: sytemctl stop firewalld setenforce 0 1.yum安装依赖: yum -y install wget openssl* gcc gc ...

  3. curl用法一例 传递代理用户名密码

    curl -u bb0e1736d66744495b814b942fd04a80:0e11dda88048ed52cc8758caf06dc6b4 https://jinshuju.net/api/v ...

  4. Java使用HTTPClient4.3开发的公众平台消息模板的推送功能

    代码引用,参考文章:http://www.cnblogs.com/feiyun126/p/4778556.html,表示感谢! package com.yuanchuangyun.cyb.manage ...

  5. 使用nodejs去做一个验证码

    let express = require('express'); let captchapng = require('captchapng'); let app = express(); app.g ...

  6. Spring学习14-源码下载地址

    今天想下载一下Spring的源代码,登录到Spring官网,傻眼了,根本找不到下载的地方!费了九牛二虎之力在网上找到了一个下载地址,记下来,免得下次再次傻找. http://s3.amazonaws. ...

  7. 研究VCL源码的原因和起点

    ---恢复内容开始--- 研究VCL源码的原因和起点 根本原因:当然是希望自己成为Delphi高手,因为这么多年过去,觉得自己始终不得要领,修改一个控件都无从下手,一直都只是个会拖控件的白痴.而我却拥 ...

  8. 洛谷P3588 [POI2015]PUS

    题面 sol:说了是线段树优化建图的模板... 就是把一整个区间的点连到一个点上,然后用那个点来连需要连一整个区间的点就可以了,就把边的条数优化成n*log(n)了 #include <queu ...

  9. python---random模块详解

    在python中用于生成随机数的模块是random,在使用前需要import, 下面看下它的用法. random.random random.random()用于生成一个0到1的随机符点数: 0 &l ...

  10. BZOJ3322[Scoi2013]摩托车交易——最大生成树+贪心+倍增

    题目描述 mzry1992 在打完吊针出院之后,买了辆新摩托车,开始了在周边城市的黄金运送生意.在mzry1992 生活的地方,城市之间是用双向高速公路连接的.另外,每条高速公路有一个载重上限,即在不 ...