美文网首页我爱编程
TypeScript 函数-可选和默认参数

TypeScript 函数-可选和默认参数

作者: 神秘者007 | 来源:发表于2018-03-19 20:06 被阅读68次

    参考网址:https://www.tslang.cn/docs/handbook/functions.html 可选参数和默认参数

    • 源码
    • Functions.ts
    //可选参数
    // function buildName(firstName:string,lastName:string) {
    //  return firstName + " " + lastName;
    // }
    // let result1 = buildName('xiaochuan','xiaoming');//'xiaochuan xiaoming'
    // let result2 = buildName('xiaochuan');//这里在编译时直接就报错了  Functions.ts(5,15): error TS2554: Expected 2 arguments, but got 1.
    // let result3 = buildName('xiaochuan','xiaoming','xiaohong');//这里在编译时直接就报错了  Functions.ts(6,15): error TS2554: Expected 2 arguments, but got 3.
    
    //上面的话传递参数的数量就必须得是 两个
    
    //下面是不确定几个参数时的写法
    //在参数名称的后面加一个 ? 号 使这个参数变为可选项
    // function buildName(firstName:string,lastName?:string) {
    //  //在这里做判断返回想应的返回值
    //  if(lastName){
    //      return firstName + " " + lastName;
    //  }else{
    //      return firstName;
    //  }
    // }
    // let result1 = buildName('xiaochuan','xiaoming');//'xiaochuan xiaoming'
    // let result2 = buildName('xiaochuan');//这里编译时就直接通过了
    // let result3 = buildName('xiaochuan','xiaoming','xiaohong');//三个参数还是同样的报错,因为超出了参数的定义数量
    
    //默认参数
    function buildName(firstName:string,lastName="xiaochuan"){
        return firstName + " " + lastName;
    }
    let result1 = buildName('xiaochuan');//编译通过  返回 'xiaochuan xiaochuan'
    let result2 = buildName('xiaochuan','xiaoming');//编译通过  返回 'xiaochuan xiaoming'
    // let result3 = buildName('xiaochuan','xiaoming','xiaohong');//编译失败  Functions.ts(33,15): error TS2554: Expected 1-2 arguments, but got 3.
    document.getElementById('pid').innerHTML = result1 + "<br/>" + result2;
    
    
    • index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>TypeScript 函数-可选和默认参数</title>
    </head>
    <body>
        <p id="pid"></p>
        <script type="text/javascript" src="Functions.js"></script>
    </body>
    </html>
    
    
    • 效果图
    image.png

    相关文章

      网友评论

        本文标题:TypeScript 函数-可选和默认参数

        本文链接:https://www.haomeiwen.com/subject/kgtmqftx.html