一、接口
通俗来说就是用来约束对象的结构,一个对象要去实现一个接口他就要去拥有接口中所约束的所有成员
interface Data {
url: string // 可以用逗号(,)、分号(;)(这里的分号同Javascript分号相同可省略)进行分割。
tit: string
subTit?: string // 可选属性,等价于subTit: string | undefind
readonly summary: string // 只读属性,初始化值后不能修改
}
function get (data: Data) {
console.log(data.url)
console.log(data.tit)
}
get({
url: 'http://www.xxx.com',
tit: 'test'
})
// 动态属性
interface Cache {
[prop: string]: string // 这里的prop不是固定的可以是任意值,只是代表了属性名称
}
const cache: Cache = {}
cache.foo = 'val1'
cache.bar = 'val2'
编译过后并不会出现在源代码中,只是用于类型约束
二、类
描述一类具体事务的抽象特征
class Person {
name: string
private age: number
protected gender: boolean
constructor (name: string, age: number) {
this.name = name
this.age = age
}
sayHi (msg: string): void {
console.log(`I am ${this.name}, ${this.msg}`)
}
}
class Student extends Person {
private constructor (name: string, age:number){
super(name, age)
console.log(this.gender)
}
static create (name: string, age: number){
return new Student(name, age)
}
}
const tom = new Person('tom', 18)
console.log(tom.name)
// console.log(tome.age)
// console.log(tome.gender)
constjack = Student.create('jack', 18)
// 访问修饰符
// private 私有属性 只能内部使用
// public 公共属性 默认为public
// protected 保护属性 只允许在子类调用
// static 静态方法