zoukankan      html  css  js  c++  java
  • 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);
    
  • 相关阅读:
    XCode4.5.6,iOS6.1下测试 判断当前设备,及其联网状态等; 关于设备插上后XCode检测不出的情况的说明
    CentOS6.3上搭建expect无交互开发环境
    CentOS6.3上安装与配置nginx+php+mysql环境
    RabbitMQ的安装与配置
    linux下用python搭建简单的httpServer
    Linux下NFS的搭建与配置
    Linux下chkconfig命令介绍
    向python文件传递参数
    数据库热备份工具innobackupex的安装
    linux yum下载RPM包后再安装LAMP环境
  • 原文地址:https://www.cnblogs.com/smart-girl/p/10342105.html
Copyright © 2011-2022 走看看