typescript 基础篇
typescript
编译器安装
cnpm install -g typescript
typescript
文件编写
新建文件夹 > demo.ts 写入以下内容
var a:string="hello Typescript"
typescript
编译
进入typescript 根目录执行以下命令 后 编译成 demo.js
tsc demo.ts
typescript
的接口的定义和继承
interface name {
Name: string,
age: number,
sin: () => string
}
var setName: name = {
Name: 'fanjiantao',
age: 24,
sin: () => { return 'hello' }
}
interface Inpoit {
name: string,
command: string[] | string | (() => string);
}
var sing: Inpoit = {
name: '范剑涛',
command: () => { return 'hello' }
}
interface nameList {
[index: number]: number
}
interface Na extends nameList {
list: nameList,
getItem: (index: number) => any
}
var infun = <Na>{};
var list = <nameList>[];
infun.list = [1, 2, 3, 4, 5]
typescript
的类的定义 ,继承 ,重写父类方法 ,类和接口的搭配
class Person {
private engine: string;
static funN: string; //静态方法可以使用 Person. 访问
// 构造方法
constructor(engine: string) {
this.engine = engine;
Person.funN = '获取发动机名称'
}
// 方法
public disp(): void {
console.log("发动机为 : " + this.engine + "\n" + Person.funN)
}
}
//继承
class Child extends Person {
name: string;
age: number;
constructor(inter: string, a: string, b: number) {
super(inter); //派生类必须使用 super 进行参数注册 否则编译出错
this.name = a;
this.age = b;
}
//重写父类的disp;
disp(): void {
//调用父类的方法;
super.disp();
}
}
// var p = new Child("ctxio", '1', 2);
// p.disp();
//类和接口
interface ILoan {
interest: number,
interFunct: () => boolean;
}
class AgriLoan implements ILoan {
interest: number;
constructor(a: number) {
this.interest = a;
}
interFunct(): boolean {
return false
}
}
typescript
的对象的定义
//对象的定义
var obj = {
name: 'fanjiantao',
age: 24,
getname:()=>string
}
//注意此处修改属性之前必须定义属性模板类型 否则编译出错
obj.getname= function(name:string){return name };
typescript
的命名空间和嵌套以及导出和引用
ts 的命名空间 使用
namespace
关键字定义 导出使用export
外部才能引用 同一命名空间下直接引用,嵌套命名空间下遵循作用域原则内部可以访问外部命名空间的下定义的类
/**typeScipt 命名空间 */
namespace someNames {
interface loneType {
name: string;
age?: number;
getNmae: () => string;
}
export class Persion implements loneType {
name: string;
age: number;
getNmae: () => string;
constructor() {
this.name = "fanjiantao";
this.age = 25;
this.getNmae = () => {
return this.name
}
}
}
}
//同一命名空间内的继承 和嵌套命名空间
namespace someNames {
//导出export
export class nace extends Persion{
}
export namespace WorkerName {
class aabb extends nace{
}
}
}
//不同命名空间内的继承
class Apersion extends someNames.Persion {
}