TypeScript(TS)语法糖之短路运算符 ||

短路运算符 ||与逻辑与是同一个符号,作用是只要符号左右两侧其中一个表达式为 true ,则该组合表达式就会返回 true,且如果第一个表达式不为空,则忽略第二个表达式。

实际代码中常用于为变量配置默认值,当||符号左边为null或undefined时,将||符号右边的{}赋值给变量,以避免定义的变量为null或undefined:

function (config) {
    /*配置 token */
    config.headers = config.headers || {};

    config.headers.Authorization = 'Bearer ' + localStorage.getItem('token');

    return config;
}

以下是测试代码可以先安装nodejs,再执行

PS C:\code\test> npm i -g typescript

PS C:\code\test> npm i -g ts-node

PS C:\code\test> set-ExecutionPolicy RemoteSigned //解除windows系统对脚本运行的限制

PS C:\code\test> ts-node .\test.ts

测试代码如下:

type ExtensionOption = {
  //isBackground: boolean
	haha:string;
}


function a(id:string,options?:ExtensionOption) {

    let option = options || {
      asServer: true,
      timeout: 8000,
      isBackground: true,
      txt: "默认文本",
    };
	console.log(id)
	console.log(option)//这里尝试下:传入asServer
	
  }
let c:ExtensionOption={haha:"我来啦"};

a("haha",c)

a("测试不传第二个参数")
PS C:\code\test> ts-node .\test.ts
haha
{ haha: '我来啦' }
测试不传第二个参数
{ asServer: true, timeout: 8000, isBackground: true, txt: '默认文本' }

curl http://172.26.5.6:3310

npm install -g nrm
nrm ls

nrm use taobao

你可能感兴趣的:(typescript,javascript,前端)