TypeScript 代码规范中的几个点

- 2 分钟前

变量声明

若后面对变量的值不做改变,最好用 const 替代 let。

函数

// 具名函数
function func(){
  // code
}
 
// 匿名函数
let func=function(){
  // code
};

// 箭头函数全都是匿名函数
let func=()=>{
  // code
};

TypeScript 中,可以使用具名函数创建一个对象,就类似于面向对象编程中的构造函数。

function Person(name,age){
   this.name=name;
   this.age=age;
}
let admin=new Person("Inger",18);
console.log(admin.name);
console.log(admin.age);

在普通函数中,this总是指向调用它的对象,如果用作构造函数,this指向创建的对象实例。而箭头函数本身不创建this,它在声明时可以捕获其所在上下文的this供自己使用。

var webName="捕获成功";
let func=()=>{
  console.log(this.webName);
};
func();

foreach

在规范中看到推荐的 foreach 写法是这样的:

const arr:string[]=['a','b','c']

arr.forEach((i) => {
  console.log(i);
});

字符串

为什么规范中建议用单引号定义字符串而不是双引号

比起用 + 拼接字符串,更推荐用 ` ` 定义字符串模版,为什么?

function test(template, name, age) {
    console.log(template);  
    console.log(name);      // name就是${Name}
    console.log(age);       // age就是${getAge()}
}
  
const Name = 'Inger';
function getAge() {
    return 23;
}
  
// 通过字符串模板的方式,可以实现字符串的拆分
console.log(`Hello ${Name}, 
	I'm ${getAge()} years old.`);
test`Hello ${Name}, 
	I'm ${getAge()} years old.`;

代码格式

Inger Notes © 2023
rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora qq quora wechat