typescript介绍

2019-04-23  本文已影响0人  琴先森的博客

基础类型

布尔值
let isDone:boolean = false;

数字
let hexLiteral:number = 0xf00d;

字符串
let name:string='bob';
还可以使用模板字符串。这种字符串是被反引号包围( ` ),并且以${expr}这种形式嵌入表达式。

let name:string = `Gene`;      
let age:number = 37;    
let sentence:string = `Hello,my name is ${name}.
I'll be ${ age + 1 } years old next month.`  

数组
let list:number[] = [1,2,3];
let list:Array<number> = [1,2,3];//数组泛型

元组Tuple
元组类型允许表示一个已知元素数量和类型的数组,各元素的类型不必相同。
let x:[string,number];
x=['hello',10]

枚举
enum类型是对typescript标准数据类型的一个补充。使用枚举类型可以为一组数值赋予友好的名字。
由枚举的值得到它的名字 enum Color {Red = 1,Green,Blue}
let colorName:string = Color[2];// 'Green'

any
let notSure: any = 4;
let list: any[] = [1, true, "free"];

void 表示没有任何类型
当一个函数没有返回值通常:

function warnUser:void{  
   alert("This is my warning message");  
} 

never 永不存在的值的类型

类型断言

let someValue:any = "this is a string";  
let strLength:number = (<string>someValue).length;  
let someValue :any = 'this is a string';  
let strLength:number = (someValue as string).length;

接口

interface LabelValue{
    label:string;
}
function printLabel(labelObj:LabelValue){
console.log(labelObj.label)
}  
let myObj = {size:10,label:"size 10 object"};
printLabel(myObj)

可选属性

interface SquareConfig{
    color?:string;
    width?:number;
}  

只读属性

interface Point{
    readonly x:number;
    readonly y:number;
}
let p1:Point = {x:10,y:20};
p1.x = 5; //error  只能在对象刚刚创建的时候修改其值,赋值后, x和y再也不能被改变了。
let a:number[]=[1,2,3,4]
let ro:ReadonlyArray<number> = a;
ro[0] = 12; //error
a= ro; //error
//但是可以用类型断言重写
a= ro as number[];

可索引的类型

interface StringArray{
    [index:number]: string;
}
let myArray:StringArray;
myArray = ["Bob","Fred"];
 
let myStr:string = myArray[0];
 
//索引签名可设为只读
readonly [index:number]: string;

继承接口

interface Shape{
    color:string;
}
interface Square extends Shape{
    slideLength:number;
}
let square = <Square>{};
square.color = 'blue';
square.slideLength = 10;

继承

class Animal{
    name:string;
    constructor(theName:string){this.name = theName;}
    move(distanceInMeters: number = 0){
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}
class Snake extends Animal{
    constructor(name:string){super(name);}
    move(distanceInMeters = 5){
        console.log("Slithering……");
        super.move(distanceInMeters)
    }
}
class Horse extends Animal{
    constructor(name:string){super(name);}
    move(distanceInMeters = 45){
        console.log("Galloping……");
        super.move(distanceInMeters)
    }
}
let sam = new Snake("Sammy the Python");
let tom:Animal = new Horse("Tommy the Palomino");
 
sam.move();
tom.move(34);

公共、私有与受保护的修饰符

class Octopus{
    readonly name:string;
}

参数属性 把声明和赋值合并至一处

存取器 get/set

静态属性
静态属性存在于类本身上而不是类的实例上。每个实例想要访问这个属性的时候,都要在origin前面加上类名,如同在实例属性上使用this.前缀来访问属性一样。

class Grid{
    static origin = {x:0,y:0};
    calculate(point:{x:number;y:number}){
        let xDist = (point.x - Grid.origin.x)
    }
}

抽象类

abstract class Department{
    constructor(public name:string){
    }
    printName():void{
        console.log('')
    }
    abstract printMeeting():void;//必须在派生类中实现
}
 
class AccountDep extends Department{
    constructor(){
        super('Accounting and Auditing')//在派生类的构造函数中必须调用super()
    }
    printMeeting(): void {
        console.log('The Accounting Department meets each Monday at 10am.');
    }
 
    generateReports(): void {
        console.log('Generating accounting reports...');
    }
 
    let department: Department; // 允许创建一个对抽象类型的引用
    department = new Department(); // 错误: 不能创建一个抽象类的实例
    department = new AccountingDepartment(); // 允许对一个抽象子类进行实例化和赋值
    department.printName();
    department.printMeeting();
    department.generateReports(); // 错误: 方法在声明的抽象类中不存在
}

模块

export {ZipCodeValidator };
export {ZipCodeValidator as mainValidator}
export * from "./StringValidator" 
 
import {ZipCodeValidator} from'./ZipCodeValidator'
import { ZipCodeValidator as ZCV } from "./ZipCodeValidator";
import * as validator from "./ZipCodeValidator";

默认导出

//JQuery.d.ts
declare let $:JQuery;
export default $;
//App.ts
import $ from "JQuery";
//OneTwoThree.ts
export default "123";
//Log.ts
import num from "./OneTwoThree.ts";

export = 和import = require()

//ZipCodeValidator.ts
let numberRegexp = /^[0-9]+$/;
class ZipCodeValidator{
    isAcceptable(s:string){
        return s.length === 5 && numberRegexp.test(s) ;
    }
}
export = ZipCodeValidator;
//Test.ts
import zip = require("./ZipCodeValidator")

编译运行

npm install -g typescript

使用Typescript编译器,名称叫tsc,将编译结果生成js文件
用 tsc filename.ts 命令

tsconfig.json文件来存储项目配置,如果运行tsc时不指定输入文件,编译器则会查找项目目录中的这个文件,如果找不到则会依次向父级目录查找。

{
    "compilerOptions":{
        "outFile":"dist/app.js",
        "sourceMap":true
    },
    "files":[
        "src/app.ts"
    ]
    //直接运行,会自动把src/app.ts编译到dist/app.js
}

如果想在typescript中直接使用npm上的js库,需要先安装Typings工具

使用webpack构建

module.exports = {
    entry:'./src/app.ts',
    output:{
        filename:'app.js',
        path:'./dist'
    },
    resolve:{
        extensions:['','webpack.js','.web.js','.ts','.js']
    },
    module:{
        loaders:[
            {test:/\.ts$/,loader:'ts-loader'}
        ]
    }
}
上一篇 下一篇

猜你喜欢

热点阅读