typeScript

typeScript由微软研发的编程语言,是 JavaScript 语言的超集,代码又最终会编译成 JavaScript 来执行

一、安装

$ npm install -g typescript

二、编译

$ tsc greeter.ts

基本类型

1、布尔

let createDone: boolean = false;    

2、数字

let createNumber: number = 10;

3、字符串

let createString: string = 'aaa';
let showString: stinrg = `hello ${createNumber}`

4、数组

let list: number[] = [1,2,3]
let listString: string[] = ['1','2','3']
let numandString: (number | string)[] = ['1',2,3]

5、元组 Tuple

允许一个已知的元素数量和类型的数据
let x: [string, number];
x = ['hello', 10]

6、枚举

enum Color { Red, Green, Blue }; 
let c: Color = Color.Green

7、任意类型 any

let notSure: any = 4;   // any 可以对不同类型的值
notSure = 'a string instead';

let list: any[] = [1, true, 'free'];
list[1] = 100

8、空值 void

void 表示没有任何类型,一个函数无返回值时返回类型是void;
function warnUser(): void(){
  console.log('...');
}

let unusable: void = undefined;

9、Object

function create(o: object | null):void;
create({ prop: 0});

10、Null 和 Undefined

let u: undefined = undefined;
let n: null = null;

11、Never 永不存在值的类型

function infiniteLoop(): never {
  while (true) {
  }
}

12、类型断言 <>、as

断言有两种写法<>和as,用来指定一个值的类型

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

解构

1、解构数组

let input = [1, 2];
function f([first, second]: [number, number]){
  console.log(first);
  console.log(second);
}
f(input);

接口

1、interface来做成定义的接口

interface SuperConfug { 
  color: string;  
  width: number;
}

function printLabel(super: SuperConfug) {
  console.log(super.color);
}
let myObj = {color: 'blud', width: 100};
printLabel(myObj);

2、readonly 表示只读,不能对其属性进行重新赋值

interface Point {  
  readonly x: number;  
  readonly y: number;
}

3、?表示属性是可选的

// [propName: string]: any 表示允许 obj[xxx] 这样的动态属性
interface SquareConfig {  
  color?: string;  
  width?: number;  
  [propName: string]: any;
}

4、函数接口

interface SearchFunc {  
  (source: string, subString: string): boolean;
}

函数

1、参数

function fn(source: string, subString: string){
  let result = source.search(subString);
  return result > -1;
}
fn('aaa', 'bbbbb');

2、为函数定义类型

function add(x: nubmer, y: number): number {
  return x + y;
}

2、索引类型

interface StringArray {
  [index: number]: string;
}
let myArray: StringArray;
myArray = ["Bob", "Fred"];

let myStr: string = myArray[0];

泛型

泛型允许延迟编写类或方法中元素的数据类型

function identity<T>(arg: T): T{
  return arg;
}

function main() {
  const result = identity<number>(1);
}

1、创建类

class Greeter {
  greeting: string;
  constructor(message: string){     // 定义message为字符串类型
    this.greeting = message;
  }
  greet(){
    return `Hello, ${this.greeting}`;
  }
}

let oGreeter = new Greeter('111');

2、继承

class Animal {
  move(distance: number = 0) {
    console.log(`Animal moved ${distance}.`);
  }
}

class Dog extends Animal {
  bark() {
    console.log('Woof! Woof!');
  }
}

const dog = new Dog();
dog.bark();
dog.move(10);
dog.bark();

3、增加了public, private(不能被外部访问), protected(不能被外部访问,只能被内部和继承访问), readonly 等访问控制修饰符

class Person {  
  protected name: string;  
  constructor(name: string) {    
    this.name = name;  
  }
}
class Employee extends Person {  
  private department: string;  
  constructor(name: string, department: string) {    
    super(name);    
    this.department = department;  
  }  
  public getElevatorPitch() {    
    return `Hello, my name is ${this.name} and I work in ${this.department}.`;  
  }
}

readonly属性:
class Person {
  readonly name: string = 'john'; // 我只读
  constructor(theName: string) {
    this.name = theName; // 可以
  }

  setName() {
    this.name = 'lili'; // 报错
  }
}

4、静态属性static

static成了所有实例共有的成员

class Person {
  static globalPeopleCount: number = '7000000000';
}
const john = new Person();
john.globalPeopleCount += 1;

const lili = new Person();
lili.globalPeopleCount // 7000000001

5、抽象类

不能被实例化的类型,目的就是用来继承

abstract class Animal {
  abstract makeSound(): void;
  move(): void {
    console.log('roaming the earch...');
  }
}

配置

1、node

$ npm install -g ts-node  // 安装ts-node来执行ts文件

$ ts-node server.ts       // 执行

2、react配置

$ npm install @types/react

2、tsconfig.json

{  
  "compilerOptions": {   
    "module": "commonjs",          // 表示这是一个 Node.js 项目,使用 CommonJS 模块机制。
    "moduleResolution": "node", 
    "target": "es6",             // 指定将代码编译到 ES6
    "rootDir": "src",            // 指定源码输入目录和编译后的代码输出目录
    "outDir": "dist", 
    "sourceMap": true, 
    "noImplicitAny": true,       // 开头的几个选项指定一些更严格的检查
    "noImplicitReturns": true, 
    "noImplicitThis": true 
  }
}

3、TSlint

$ npm install tslint -g

根目录创建tslint.json:
{  
  "extends": [ "tslint:recommended" ],  
  "rules": {    
    "no-console": [ false],    
    "only-arrow-functions": [ false ] 
  }
}

$ tslint --fix src/**/*.ts      // 执行

4、webpack中使用

$ npm install ts-loader typescript --save-dev

webpack.config.js

module.exports = {
  entry: './app.ts',
    output: {
    filename: 'bundle.js'
    },
    resolve: {
      extensions: [ '.ts', '.tsx', '.js' ]
    },
    module: {
      loaders: [     
        {
          test: /.tsx?$/
          loader: 'ts-loader'
        }    
      ]
    },
  };

tsconfig.json中配置

{  
  "compilerOptions": {    
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es6",
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true  
  }
}

5、小程序

https://segmentfault.com/a/1190000008175944

| https://github.com/semlinker/awesome-typescript // 合集
| https://zhongsp.gitbooks.io/typescript-handbook/doc/handbook/Basic%20Types.html
| https://mp.weixin.qq.com/s/Oyawvb5BD-OKvMuF2tQ0pw?
| https://www.jianshu.com/p/f317a3c01b58