typescript函数(笔记非干货)
函数类型
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函数(笔记非干货)的更多相关文章
- typescript枚举,类型推论,类型兼容性,高级类型,Symbols(学习笔记非干货)
枚举部分 Enumeration part 使用枚举我们可以定义一些有名字的数字常量. 枚举通过 enum关键字来定义. Using enumerations, we can define some ...
- typescript基础类型(学习笔记非干货)
布尔值 Boolean let isDone:boolean=false; 数字 Number let decLiteral:number=6; let hexLiteral:number=0xf00 ...
- typescript泛型(学习笔记非干货)
软件工程中,我们不仅要创建一致的定义良好的API,同时也要考虑可重用性. 组件不仅能够支持当前的数据类型,同时也能支持未来的数据类型, 这在创建大型系统时为你提供了十分灵活的功能. In softwa ...
- typescript类(学习笔记非干货)
我们声明一个 Greeter类.这个类有3个成员:一个叫做greeting的属性,一个构造函数和一个greet方法. We declare a Greeter class. This class ha ...
- typescript接口(学习笔记非干货)
typescript的核心原则之一就是对所具有的shape类型检查结构性子类型化 One of the core principles of typescript is to check struct ...
- typescript变量声明(学习笔记非干货)
var a=10; function f(){ var message="hello,world"; return message; } function f(){ a=10; r ...
- Typescript 学习笔记三:函数
中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...
- mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)
最后更新时间:2017-07-13 11:10:49 原始文章链接:http://www.lovebxm.com/2017/07/13/mongodb_primer/ MongoDB - 简介 官网: ...
- Typescript 学习笔记二:数据类型
中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...
随机推荐
- 记录:EM 算法估计混合高斯模型参数
当概率模型依赖于无法观测的隐性变量时,使用普通的极大似然估计法无法估计出概率模型中参数.此时需要利用优化的极大似然估计:EM算法. 在这里我只是想要使用这个EM算法估计混合高斯模型中的参数.由于直观原 ...
- mysql操作命令梳理(1)-索引
1.创建索引索引的创建可以在CREATE TABLE语句中进行,也可以单独用CREATE INDEX或ALTER TABLE来给表增加索引.以下命令语句分别展示了如何创建主键索引(PRIMARY KE ...
- php7与之前的区别和更新【转】
http://blog.csdn.net/u011957758/article/details/73320083 本文是一篇讲座听后+后续研究的总结. 话说当年追时髦,php7一出就给电脑立马装上了, ...
- Note: SE Class's Individual Project
虽然第一个Project还有点小问题需要修改,但是大体已经差不多了,先把blog记在这里,算是开博第一篇吧! 1.项目预计的用时 本来看到这个题的时候想的并不多,但是看了老师的要求才觉得如此麻烦ORZ ...
- rabbitMq实现与zookeeper类似的watcher功能
场景:A.B.C.D(可以是一个机器的不同进程,也可以是不同机器的进程)启动了相同的项目,使用同一个数据库.但是,如果A修改了数据库的数据,需要B.C.D在很短的时间能够知道数据库发生了修改.当然可以 ...
- 【转】七牛免费SSL证书,配置自定义域名CDN加速
原文链接:https://excaliburhan.com/post/use-qiniu-ssl-and-cdn.html 申请七牛SSL证书 其实,七牛在很早之前就支持CDN使用https,但是他要 ...
- Odoo中连接mysql数据库
how to integrate Odoo with MySQL - Stack Overflowhttps://stackoverflow.com/questions/31959919/how-to ...
- Facebook 50%用户是虚假账号?我觉得可以更高!
0x00 背景 今天下午看新闻时,无意看到一条关于facebook虚假帐号(fake account)消息: 一下子就被这标题吸引了眼球,因为作为一个第三方机构,能够对facebook这样如此海量的帐 ...
- 键盘事件(keyup、keydown、keypress)
1.onkeyup 和onkeydown时,keyCode是不区分大小写的,会将小写字母自动转化为大写字母. 2 onkeypress时,区分大小写. 3兼容event.keyCode||event. ...
- linux服务器上安装python 3.6.3
一.下载源码包 地址https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz 二.解压源码包 1.下载解压工具xz #yum -y ins ...