classPoint{public x:numberpublic y:numberconstructor(x:number,y:number){this.x = x
this.y = y
}publicgetPosition(){return`(${this.x},${this.y})`}}const point =newPoint(1,3)console.log(point.getPosition())// (1,3)
继承类
classParent{public name:stringconstructor(name:string){this.name = name
}}classChildextendsParent{constructor(name:string){super(name)}}
classStudentInfo{public name:stringpublic age?:numberconstructor(name:string,age?:number,sex?:string){this.name = name
this.age = age
}}// 属性名后添?,参数变成可变参数,在类实例化对象的时候,可变参数,可以根据实际情况选择,是否传入参数// 可变参数即使在不传入参数的情况下,会默认给未传入的参数赋值undefinedconst stInfo1 =newStudentInfo('ls')const stInfo2 =newStudentInfo('ls',18)const stInfo3 =newStudentInfo('ls',18,'女')
存取器
typescript存取器等同于ES6中的存取器
classStudentInfo{public name:stringpublic age?:numberconstructor(name:string,age?:number,sex?:string){this.name = name
this.age = age
}getinfoStu(){return`${this.name}: ${this.age}`}setinfoStu(value){console.log(`setter: ${value}`)// 18this.name = value
}}// 属性名后添?,参数变成可变参数,在类实例化对象的时候,可变参数,可以根据实际情况选择,是否传入参数// 可变参数即使在不传入参数的情况下,会默认给未传入的参数赋值undefinedconst stuInfox =newStudentInfo('zs',18,'男')console.log(stuInfox.infoStu)// zs: 18
stuInfox.name ='tq'console.log(stuInfox.infoStu)// tq: 18
抽象类
抽象类被其他类继承,使用abstract定义抽象类
abstractclassPeople{constructor(public name:string){}publicabstractprintName():void}// 无法创建抽象类的实例// const pl = new People()classManextendsPeople{constructor(name:string){super(name)this.name = name
}publicprintName(){console.log(this.name)}}const me =newMan('zs')
me.printName()// zs
abstractclassPeople{constructor(public name:string){}publicabstractprintName():void}// 无法创建抽象类的实例// const pl = new People()classManextendsPeople{constructor(name:string){super(name)this.name = name
}publicprintName(){console.log(this.name)}}const me =newMan('zs')
me.printName()// zs