typescript入门

为何要使用 typeScript?

  • 我们定义一个函数,仅仅只是操作字符串,但是人总会疏忽,在js中传递进去对象,函数也一样能运行
  • 由此,我们需要一个在运行前帮我们检查,并约束数据类型的语法
  • 在 angular里面1更名为 angular,2以上都称之为 angularlO

快速起步

  • 安装编译 TypeScript语法到s语法的编译工具

    npm install -g typescript
    

    编写代码

    function greeter(person: string) {
    return "He11o," + person;
    }
    let user = "Jane User";
    document.body.innerHTML = greeter(user);
    
  • 编译代码

    tsc greeter.ts
    
  • 可以编译的文件后缀.ts || .tsx || .d.ts

常见错误处理

类型

1. 布尔值

2. 数字

let decLiteral: number = 6;

3. 字符串

let name: string = "bob" ;

数组

let list: number[] = [1, 2,3];

任意类型数组

let arr : any[] = ['a' ,1, true];

枚举

enum Color {Red, Green, Blue}
let C: Color = color. Green; //1
let msg :string = co1or[1]; // Green

void

  • 一般是作为函数没有返回值的表示, 而不作为变量类型的声明
  • 因为它表示没有任何类型
function warnUser(): void {
  	alert("This is my warning message") ;	
}

Null和Undefined


类型断言

类型断言有两种形式。其- 是"尖括号语法:

let somevalue: any = "this is a string" ;

let str: string = <stri ng>someValue;

另一个为 as 语法:

let someValue: any = "this is a string";
let str: string = someValue as string;

基本使用(里面不要放let/const这些)

class Greeter{
    greeting: string;
    constructor(message: string) {
        this greeting= message;
    }
    greet() {
    		return"Hello,"+ this greeting;
    }
}
let greeter new Greeter("world")

继承语句

class student extends Person {}
new Student();

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

访问修饰符与继承无关,只要符合继承规则都能访问public属性可以在任意代码范围访问class外其他class,目前可以理解到继承的class

private只能在自己的class中访问

protected可以在自己和子类中被访问

公共(默认和不写一样)

  • public代表可以在class{} 以外的地方访问
class Anima 1 {
		pub1ic name: string =' abc' ;
}
new Animal().name; //可以访问

privated

class Anima1 {
    private name : string = 'Cat' ;
    public show() {
    	console.1og( ${this.name}' ); //只能在class内访问
		}
}
new Animal().show(); //ok
new Animal().name; //wrong:'name' is privated

protected

class Anima1 {
	protected name : string = '动物';
  pub1ic age : number = 18;
}
class Dog extends Animal {
	pub1ic showName() {
		console.log(this.name); //只有在儿子里面才能访问}
	}
}
let dog = =new Dog() ;
console. log(dog. age); //公有可以访问
console.1og(dog. name); //错误,只有在儿子里面才能访问dog.showName() ;

readonly

  • 类似于之前我们使用的const,只能被赋值一次, 不能再被赋值
class octopus {
		public readonly name: string = 'abc';
}
let dad = new octopus();
dad.name = "Man with the 3-piece suit"; //错误! name是只读的.

get/set存取器

  • Accessors are only available when targeting ECMASCript 5 and hi gher

    因为默认使用的是ES3的代码规范编译,可以提高ES代码规范的版本

    tsc -t ES5 test.ts
    
  • 可以运行

class Xxx {
    private _age: number;
    get age(): number {
    		return this._age;
    }
    set age(newAge: number) {
        if (newAge > 0 && newAge < 100) {
            this._age = newAge;
        } else {
            console. log("非法年龄");}
        }
    }
}
let Xxx = new xxx();
Xxx.age = 12;

静态属性

  • 使用类名,属性名访问
  • 类似构造函数的属性 function P(){}; P.xxx= ‘123’。
  • 静态属性不是实例的属性 function P(){}; p.prototye.xxx= ‘123’
  • 组合写法
class xxo {
		public static readonly name :string = '123';
}
Xxx. name

小结: public/ readonly这类修饰符是在编译过程中对代码的约束,而不能管到编译后约束;静态不能访问实例,实例可以访问静态

抽象类
  • 每个class的属性定义都很随意。可以通过抽象类来管理其必备那些属性及方法

  • 抽象类中可以有抽象方法(给子类实现) ,也可以有已实现的方法

    abstract class Animal {
        abstract makeSound(): void;
        move(): void {
          console. log(' roaming the earch...');
        }
    }
    
    • 第2行:子类必须实现,或者子类也是抽象类并声明该方法为抽象方法接口(约定、规范)
    • 只定义,不实现的抽象类
    • 接而可以用来实现,而不是继承,所以对应类必须实现接口中的方法和属性

类实现接口

  • -个类只能继承-一个类(单继承),一个类可以实现多个接口,都是定义规则
interface ClockInterface {
		currentTime: Date;	
}
class Clock implements ClockInterface {
		currentTime: Date ;
		constructor(h: number, m: number) { }
}

接口继承接口

interface Shape {
		color: string;
}
interface Square extends shape {
  	IsideLength: number;
}
class Xxx imp1ements Square {
  	sideLength: number;
		color: string;
}
  • 最上层定义接口(规范/约定)
    • 第二层,当前实现了-部分,有一部分只能更具象的层来实现抽象类
    • 第三层,普通类,自己统一实现

泛型

定义类和函数时,我自己都不知道什么类型,由使用者决定

泛型方法

function identity<T>(arg: T): T {
		return arg;
}
1et output = identity<string> ("myString");

泛型类

class Test<T,S> {
		public xxx:T; // T改为any这个xxx- 辈子都可以是任意类型
  	add:(x:S) => s;
}
let test = new Test<number,string>() ;
test.xxx = 123;
  • num:Person这样的自定义类型
  • T就可以传递Person
  • any是任意的数据类型,这个函数或者这个类中使用的变量类型是永远任意
    • 使用泛型后,代表留空,使用的时候填入,这个类和函数中,使用的变量类型永远是填入的
    • any是任意的,泛型是这次填入的挂钩-次
posted @ 2019-06-07 19:45  南山道士  阅读(65)  评论(0编辑  收藏  举报