声明数组
1
| var numlist:number[] = [2,4,6,8]
|
如果元素不同,则是元组
联合类型
接口(interface)
一系列抽象方法的声明,是一些方法特征的集合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| interface IPerson { firstName: string, lastName: string, sayHi: () => string }
var customer: IPerson = { firstName: "Tom", lastName: "Hanks", sayHi: (): string => { return "Hi there" } }
console.log(customer);
|
联合类型+接口
1 2 3 4 5 6 7 8 9 10
| interface IPerson { name: string | string[] sayHi: () => string | void }
var customer: IPerson = { name: ["Hanks", 'aa'], sayHi: (): void => { } } console.log(customer);
|
数组+接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| interface A { [index: number]: string | number } const a: A = ['1', 1] const b = { '0': '1', '1': 1 } console.log(a,b);
interface namelist { [index: number]: string }
const list2: namelist = ["Google", "Runoob", "Taobao"]
|
接口继承
1
| Child_interface_name extends super_interface1_name, super_interface2_name,…,super_interfaceN_name
|
类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Car { engine:string; constructor(engine:string) { this.engine = engine } disp():void { console.log("函数中显示发动机型号 : "+this.engine) } }
var obj = new Car("XXSY1")
console.log("读取发动机型号 : "+obj.engine)
obj.disp()
|
TS一次只支持继承一个类,并不支持一次继承多个类,这一点区别于TS接口
继承
super是对父类的直接引用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Father { name: string job: string constructor(name: string, job: string) { this.name = name this.job = job } doJob(job: string | void): string { job = job || this.job console.log('我正在做' + job); return '我正在做' + job } }
class Son extends Father { constructor(name: string, job: string) { super(name, job) } doJob(): string { console.log('我正在学' + this.job); return '我正在学' + this.job } fatherJob(): void { super.doJob('监督儿子' + this.job + '的工作') } }
const f = new Father('Bob', '司机') f.doJob() const s = new Son('Mack', 'Ts') s.doJob() s.fatherJob()
|
访问控制
- public(默认) : 公有,可以在任何地方被访问。
- protected : 受保护,可以被其自身以及其子类访问。
- private : 私有,只能被其定义所在的类访问。
实现接口(implements)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| interface ILoan { interest:number } class AgriLoan implements ILoan { interest:number rebate:number constructor(interest:number,rebate:number) { this.interest = interest this.rebate = rebate } } var obj = new AgriLoan(10,1) console.log("利润为 : "+obj.interest+",抽成为 : "+obj.rebate )
|
对象
1 2 3 4 5 6 7 8 9 10
| ts中对象是事先定义好的模板,不能自己再添加属性 const m = { x: 1, } m.a = () => { console.log(1);
}
|
type类型别名
1 2 3 4 5 6 7 8 9
| type AB = { name?: string, age: number, c: '1' | 2 } const d: AB = { age: 1, c: 2 }
|
泛型
一个简单的泛型例子:
1 2 3 4 5 6
| function func<T,k>(a: T, b: K): k { return b }
console.log(func("1", "2"));
|
泛型接口:
1 2 3 4 5 6 7 8 9 10 11
| interface HasLength { length: number }
function func<T extends HasLength>(a: T): number { return a.length }
func("123") func({length:222}) func(123)
|