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('abc')
hello(18)
2、接口继承
interface Parent{
prop1:string
prop2:number
}
interface Child extends Parent{
prop3:string
}
const myObj:Child={
prop1:'',
prop2:1,
prop3:''
}
3、类的修饰符
static属于类本身的变量
protected当前类和子类可使用,属于实例变量
private当前类可使用,属于实例变量
class Article{
public title:string
content:string
aaa?:string
bbb=100
private tempData?:string
protected innerData?:string
static author2:string
private static readonly author:string='zg'
constructor(title:string,content:string){
this.title=title
this.content=content
}
}
const a=new Article('标题','内容')
class B extends Article{
constructor(title:string,content:string){
super(title,content)
console.log(this.innerData)
console.log(Article.author2)
}
}
4、存储器
也就是get、set方法
class User{
private _password:string='123456'
get password():string{
return this._password
}
set passwrod(newPass:string){
this._password=newPass
}
}
const u=new User()
console.log(u.password)
5、抽象类
abstract class Animal{
abstract name:string
abstract maskSound():void
move():void{
console.log('移动')
}
}
class Cat extends Animal{
name:string='小猫'
maskSound():void{
}
}
6、类实现接口
interface Animal{
name:string
get sound():string
makeSound():void
}
interface B{
age:number
}
class Dog implements Animal,B{
name:string='小狗'
age:number=10
get sound(){
return ''
}
makeSound():void{
}
}
7、泛型类
class MyClass<T>{
public value:T
constructor(value:T){
this.value=value
}
do(imput:T):T{
console.log("处理数据",this.value)
return imput
}
}
const myStr=new MyClass<string>('hello')
myStr.do('abc')
const myNum=new MyClass<number>(123)
myNum.do(456)