和JavaScript中的一些区别
- 加强了对类中属性的类型的限制
- 必须要定义属性
实例:
class Person {
// 定义属性
name:string
age:number
gender:string
//对构造函数中传入的参数个数(3个),参数类型(string,number,string),做了一些限制
constructor(name:string='旺旺',age:number=13,gender:string='狗'){
this.name = name
this.age = age
this.gender = gender
}
// 方法
sayHi(str:string){
console.log(`我叫${this.name},我今年${this.age},我是${this.gender},${str}`);
}
}
let person:Person = new Person('喵喵',12,'一只猫');
person.sayHi('你好啊') // 我叫喵喵,我今年12,我是一只猫,你好啊
- 上面定义的类中的构造函数对传入的参数个数(3个),参数类型(string,number,string),做了一些限制 。