ts接口

接口是对象的状态(属性)和行为(方法)的 抽象(描述)
接口是一种类型,是一种规范,是一种规则,是一种能力,是一种约束
readonly VS const
最简单判断使用readonly还是const的方法是看要 把他作为变量还是作为一个属性,作为变量的使用const。作为属性的使用readonly
(()=>{
    //定义一个接口,该接口作为person对象的类型使用,限定或者约束该对象中的属性数据
    //readonly代表只读,?代表可有可无
    interface IPerson{
        readonly id:number    //只读
        name:string
        age:number
        sex?:string    //可以没有
    }

    const person:IPerson={
        id:1,
        name:'jerry',
        age:18,
        sex:'女 '
    }
})()

(function(){
    //描述一个对象的类型
    type myType = {
        name:string,
        age:number
    }
    //接口用来定义一个类的结构
    //接口中的所有的属性都不能有实际的值
    //接口只定义对象的属性,而不考虑实际值
    //在接口中所有的方法都是抽象方法
    interface myInterface{
        name:string;
        age:number;
    }

     interface myInterface{
        gender:string;
    }
    const  obj:myInterface = {//内容的属性和方法要和接口定义中的一致
        name:'sss',
        age:111,
        gender:'男'
    }
})()


(function(){
 
    //定义类 时,可以使用类去实现一个接口;implements:实现
    //实现接口就是使类满足接口的要求
    interface MyInter{
        name:string;
        sayHello():viod;
    }
    class  MyClass  implements myInter{
        name:string;
        constructor(name:string){
            this.name=name
        }
        sayHello(){
            console.log("大家好~")
        }
    }
})()

//属性的封装
(function(){
    class  Person{
    //TS可以在属性前添加属性的修饰符
    //public修饰的属性可以在任意位置访问(修改,包括子类),默认值,
    //private私有属性,只能在类内部进行访问(修改 )
    //    可以在类中添加方法使得私有属性可以被外部访问
    //protected 受保护的属性,只能在当前类和当前类的子类当中访问 (修改)
        private name:string;
        age:number;
        constructor(name:string,age:number){
            this.name=name;
            this.age=age;
        }
        getName(){
            return this.name
        }
    }
//现在属性是在对象中设置的,属性可以任意的被修改
//属性可以任意被修改将会导致对象中的数据变得非常不安全
consr per = new  Person("孙悟空",18);
per.name="猪八戒";
per.age=-38;
console.log(per)

const per = new Person("孙悟空 ",18);
console.log(per.getName())

class A{
    protected num:number;
    constructor(num:number){
      this.num = num  
    }
}
class B extends A{
    
    test(){
        console.log(this.num)
    }
}
const b = new B(123)
b.num=123//访问不了,报错

class C{
    //可以直接将属性定义在构造函数中,下边的this.name=name这种就不用写了
    constructor(public name:string,public age:number){
    }
}
/*和这些代码是等价的
class C{
    name:string;
    age:number;
    constructor(name:string,age:number){
        this.name=name;
        this.age=age;
    }
}
*/
const c = new C("aily",11)
console.log(c)
})();

  

posted @ 2022-06-23 18:16  韩Jeor  阅读(151)  评论(0编辑  收藏  举报