TypeScript面向对象 -- object对象、interface接口、class类
object 对象类型
-
不是 key - value 的形式
-
而是 key - type 的形式
-
let person = { age: 18, name: 'three zeros' } // 赋值类型与定义时的类型不同时,会报错 person.age = '22' // 使用不存在的属性,会报错 console.log(person.address)
interface 接口
-
在 TypeScript 中,使用接口
interface
来定义对象的类型 -
// 定义接口 interface IPoint{ x:number; y:number } let drawPoint = (point:IPoint) => { console.log({ x: point.x, y: point.y }) } // 正常使用 drawPoint({x:25,y:153}) // 类型与接口定义的不同、报错 drawPoint({x:'three zeros',y:'coding fun'}) // 属性与接口定义的不同、报错 drawPoint({a:327,b:263})
class 类
-
接口相当于一份说明书,接口中定义的变量和方法都需要在类中实现
-
在类中实现接口定义的方法 关键字:
implements
-
interface IPoint{ x:number; y:number; drawoPoint:() => void; getDistances:(p:IPoint) => number; } class Point implements IPoint{ x:number; y:number; // 构造器 constructor(x:number,y:number){ this.x = x; this.y = y; } // 实现接口方法 drawoPoint= () => { console.log('x',this.x,'y',this.y) }; // 实现接口方法 getDistances= (p: IPoint)=>{ return p.y } } // 实例使用 const point = new Point(20,80) point.drawoPoint() console.log(point.getDistances(point))