TypeScript(2)

发布时间 2023-12-07 16:13:00作者: Karle

1.类型

//rename data type
type NAME = string
const jackName : NAME = 'Jack Jay'

//rename mixed data type
type PHONE = string | number
const jackPhone : PHONE = '123321'
const maryPhone : PHONE = 121212

//like interface
type Person = {
    name:string,
    age:number
}
const jack : Person = {
    name:'Jack',
    age:12
}

// cannot rewrite and mixed
// throw error
type Rewrite = {
    name:string
}
type Rewrite = {
    age:number
}

// cannot extends but can mixed
interface Father {
    name:string
}
type Son = Father & {
    age:number
}
const john : Son = {
    name:'',
    age:12
}

2.元组

//confirm each type of element in array and length
const arr : [string,number,boolean] = ['123',123,true]
arr[0].split('')
arr[1].toFixed(2)

3.类

  3.1 public private protected

// public: everyone can use
// private: only the class inside which inited it can use
// protected: the calss inited and the sub class can use
class Person {
    public name = 'Person'
    private age = 18
    protected phone = 12345
}
class Jack extends Person {
    log() {
        console.log(this.name)
        console.log(this.age)
        console.log(this.phone)
    }
}
const jack = new Jack()
jack.log()

  3.2 class使用数据类型

//must init the value before use constructor
//class use data type
class Animal {
    public name
    constructor(name:string) {
        this.name = name
    }
}

  3.3 readonly

// only can be changed in constructor
class Book{
    public readonly name
    constructor(name:string) {
        this.name = name
    }
}

  3.4 abstract

// abstract class can't be inited
// abstract method must be rewrite by sub class
abstract class Animal {
    public name
    constructor(name:string) {
        this.name = name
    }
    public abstract eat() : any
}
class Dog extends Animal {
    public age
    constructor(name:string,age:number) {
        super(name)
        this.age = age
    }
    public eat() : any {
        
    }
}
const dog = new Dog('123',123)