TypeScript 函数-可选和默认参数

参考网址: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>
  • 效果图
1514821767(1).jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 金秋国庆,全民同乐,我们一家三口为“十一”去哪儿商议了很久。希爸想去阳江海陵岛,女儿想去香港迪士尼,我想去...
    斐梦阁主阅读 3,899评论 0 3
  • 01 林石!你有没有听我讲话呀。 唐小米发怒了。 林石把目光从手机上收回来,安抚唐小米,听了呀。 那我说的什么?唐...
    开皮卡的王姑娘阅读 4,130评论 0 33
  • 二姐从垦利回家置办家什,外甥女刚生了小宝宝。和二姐视频得知还缺一个包袱,一下想起我家就有,多年前娘给我做的,说留个...
    风和日丽_5521阅读 3,593评论 1 3
  • 上周魅力微讲师的第一课,虽然没有见过张文峰老师,可是张老师的话句句说到心坎里,让我能感受到他的真诚和真实。以前自己...
    九月微尘阅读 1,722评论 0 3