自学内容网 自学内容网

typescript进阶

typescript进阶

#函数重载
#参数类型和反应值不同的函数
#接口继承
#类的修饰符
#存取器
#类实现接口
#抽象类
#泛型类

#函数重载
#参数类型和反应值不同的函数
function hello (name: string) : string
function hello (age: number) : string
function hello (value: string | number ) : string {
    if (typeof value == 'string') {
        return 'hello,my name is ' + value 
    }else if (typeof value == 'number'){
        return `hello,my age is ${value}`
    } else {
        return 'Illegal format'
    }
}
let retValue = hello('abc')
console.log(retValue)
let retValue2 = hello(18)
console.log(retValue2)

[LOG]: "hello,my name is abc" 
[LOG]: "hello,my age is 18" 


#接口继承
interface Parent {
    prop1: string
    prop2: number
}


interface Child extends Parent {
    prop3: string
}

const myObj: Child = {
    prop1: '1',
    prop2: 1,
    prop3: 'a'
}


#类的修饰符
class Article {
    public title: string
    content: string
    aaa ?: string
    bbb = 100

    private tempData ?: string
    protected innerData ?: string

    static author: string
    private static author2: string
    private static readonly author_readonly: string = 'aa'

    constructor (title: string,content: string) {
        this.title = title
        this.content = content
        Article.author2 ='1'
        /*Article.author_readonly ='2'*/
    }
}

const a = new Article('title','content')
Article.author = '111'

class B extends Article {
    constructor (title: string,content: string){
        super(title,content)
        this.innerData ='1'

    } 
}

#存取器
class User {
    private _password: string = ''
    get password(): string {
        return '******'
    }
    set password(newPass: string){
        this._password = newPass
    }
}

const u = new User()
u.password='111111'
console.log(u.password)


#抽象类
abstract class Animal {
    abstract name: string
    abstract makesound(): void
    move(): void {
        console.log('move')
    }

}

class Cat extends Animal {
    name: string = 'cat'
    makesound():void{

    }
}

#类实现接口
interface Aninmal{
    name: string
    get sound(): string
    makeSound():void

}
interface B{
    age: number
}

class Dog implements Aninmal,B {
    name: string = 'dog'
    age: number = 10
    get sound() {
        return ''
    }
    makeSound():void{

    }
}

#泛型类
class MyClass {
    value: string
    constructor (value: string) {
        this.value = value

    }
    do(){
        console.log('manage data',this.value)
    }
}


class MyClass2<T> {
    public value: T
    constructor (value: T) {
        this.value = value

    }
    do(input: T):T {
        console.log('manage data',this.value)
        return input
    }
}

const myStr = new MyClass2<string>('hello')

myStr.do('11')
/* myStr.do(11) */

const myNum = new MyClass2<number>(11)

/* myNum.do('11') */
myNum.do(11)

原文地址:https://blog.csdn.net/u014785520/article/details/144034190

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!