1、类(Class)
类是ts的核心,使用ts开发时,大部分代码是写在类里面的。
类的定义、构造函数、类的继承;
类的定义:
class Person{
constructor(public name: string) { //在构造函数里要写访问控制符
this.name = name
console.log("hahhahah")
}
eat() {
console.log("eatttttt")
}
}
var p1 = new Person('zx');//实例化
p1.name = 'zx';
p1.eat();
继承:
class Person{
constructor(public name: string) { //在构造函数里要写访问控制符
this.name = name
console.log("hahhahah")
}
eat() {
console.log("eatttttt")
}
}
class Employee extends Person{
constructor(name: string, code: string) {
super(name); //必须要有susuper
console.log('xxxx')
this.code = code;
}
code: string;
work() {
super.eat();
this.dowork();
}
dowork() {
console.log('iam working')
}
}
var e1 = new Employee("dd",'ss');
泛型(generic)
参数化的类型,一般用来限制集合的内容
比如:
var workes:Array<Person>=[]; //规定workes里只能是person类型的数组
workes[0] = new Person('zx);
workes[1]=new Employee('dd','s');
workes[2]=2;//会报错,它只能接受person 类型的数组
接口(Interface)
用来建立某种代码约定,使得其他开发者在调用某个方法或创建新的类时必须遵循接口所定义的代码约定;
用接口声明属性:
interface IPerson{
name: string;
age: number;
}
class Person{
constructor(public config: IPerson) {
}
}
var p1 = new Person({
name: 'zx',
age:12
})//多传或者少传都会报错,要遵循接口声明的属性
用接口实现类的方法: implements
interface Animal{
eat();
}
class dog implements Animal{
eat() { //必须要实现接口里的eat方法
console.log('dddd')
}
}
模块(Module)
模块可以帮助开发者将代码分割为可重用的单元。开发者可以自己决定将模块中的哪些资源(类、方法、变量)暴露出去供外部使用,哪些资源只在模块内使用
export import 来控制
类型定义文件(*.d.ts)
类型定义文件用来帮助开发者在ts中使用已有的js的工具包
如JQuery
github.com/typings
网友评论