TS进阶1
//1、函数重载 function hello(name:string):string function hello(age:number):string function hello(value : string | number): string { if (typeof value === 'string') { return '你好,我的名字是'+value } else if (typeof value === 'number') { return `你好,我的年龄是${value}` } else { return '非法格式' } } hello(32) hello('aidon') //2、接口继承 interface Parent { prop1:string prop2:number } interface Child extends Parent { prop3:string } const MyObj:Child = { prop1:'', prop2:1, prop3:'' } //3、类 // 类的修饰符 class Article { public title:string //公开的 任何地方可以访问 默认给public content:string aaa?:string //可选 bbb = 100 //可选 默认给100 number类型 private tempDate?:string //私有的,只能在类Article内部访问 protected innerData?:string // 受保护,只能在类Article及子类中访问 static author:string //静态属性,将属性设置给类本身,而不是设置给类的实例 private static author1:string // 私有的静态属性 private static readonly author2:string= 'qqqqq' // 私有的 静态的 只读属性 不能对其在进行赋值 constructor (title:string,content:string){ this.title = title this.content = content } } const a = new Article('标题','内容') a.aaa = '123' a.bbb = 123 Article.author = 'qqq' // 不能a.auchor //a.tempDate a.innerData class Bo extends Article { constructor (title:string,public content:string) { // 也可以在这里私有属性,但是不建议 super(title, content) this.innerData = "123" } } //4、存取器 class User { private _password:string = "" //私有属性一般给一个下划线 get password():string { //不能读取 读取的话 给个***** return "******" } set password(newPass:string){ // 可以修改重写 this._password = newPass } } const u = new User() console.log(u.password) // 不能访问_password //5、抽象类 abstract abstract class Animal { abstract name: string abstract maskSound():void move():void { console.log('移动'); } } class Cat extends Animal { name:string = "小猫" maskSound(): void { } } //6、类实现接口 interface Animal1 { name:string //普通的属性 get sound():string // 存储器 makeSound():void // 普通的方法 } interface B { age:number } class Dog implements Animal1,B { name:string = '小狗' age:number = 5 get sound(){ return "" } makeSound(): void { } } //7、泛型类 class MyClass<T> { public value:T constructor (value:T) { this.value=value } do (input:T):T { console.log("处理数据",this.value); return input } } const myStr = new MyClass<string>("hello") myStr.do("abasdf") const myNUm = new MyClass<number>(11111) myNUm.do(22222)