TS 笔记

2019-06-05  本文已影响0人  天涯笑笑生

一、简介

npm install -g typescript

查看版本号

tsc -V

二、hello world

注:IDE 使用VSC,安装TypeScript 插件
新建hello.ts

const message:string = 'Hello World'
console.log(message)

编译

tsc hello.ts

编译后的文件默认在同级目录下hello.js

var message = 'Hello World';
console.log(message);

ES6属性没有保留,需要配置参数

tsc hello.ts --target es6

也可以使用tsconfig.json 配置文件,手动创建或者自动生成

tsc -init

三、 数据类型

// 布尔值
let isLogin: boolean = false

// 数字
let userAge: number = 18

// 字符串
let userName: string = 'Jony'

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

// 元组Tuple
// 当访问一个越界的元素,会使用联合类型替代
let tuple: [string, boolean, number] = ['a', true, 8]
tuple = ['a', true, 8]

// 枚举
enum Color {Red, Green, Blue}
let oneColor: Color = Color.Blue

//自动递增,或者全部手动赋值
enum Province {
    BeiJing = 1,
    Tianjin,
    Nanjing
}

let cityName: string = Province[3]
console.log(`cityName: ${cityName}`)

// Any
let notSureValue: any = 4
notSureValue = 'maybe a string instead'
notSureValue = false

let anyTypeList: any[] = [1, true, 'b']

// Void
//与any 相反,没有任何类型,一般用于没有返回值的方法
//void变量只能赋值undefined 或null
let unusable: void = undefined

// Null & Undefined
// 和void 相似
// 默认是所有类型的子类型

// Never
// 表示用不存在的值的类型

// Object
// 非原始类型

类型断言

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

console.log(strLength) //16

四、 变量声明

五、 接口

interface People {
    readonly num: string //只读
    name: string
    age?: number //可选
    commandline?: string|string[]|(()=>string) //联合类型
    [propName: string]: any //可索引属性,索引可以是字符串或数字
}

let people: People = {
    num:'001',
    name:'sufei'
}
people.age = 12
people.commandline = () => `hello ${people.name}`

// people.num = '002'

//继承
enum Grade {A, B, C}
interface Student extends People {
    grade?: Grade
}

let student: Student = {
    num: '003',
    name: 'zhang',
    grade: Grade.A
}

六、 类

class Animal {
    //属性
    name: string
    
    //构造函数
    constructor(name:string) {
        this.name = name
    }

    //方法
    play():void {
        console.log(`${this.name} play`)
    }
}

//创建实例
let animalA = new Animal('A')
animalA.play()

//继承
class Dog extends Animal{

    //方法重写
    play():void {
        console.log(`A dog named ${this.name} is playing`)
    }
}

let dogA = new Dog('A')
dogA.play()

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

static 静态属性

readonly修饰符

存取器

class Person {

    private _name:string

    get name(): string {
        return this._name
    }

    set name(newName: string) {
        this._name = newName
    }
}

let person = new Person()
person.name = 'zuozhu'
console.log(person.name)

instanceof 运算符

抽象类

七、函数

function buildName(firstNmae:string = 'unknown', lastName?:string, ...restOfName: string[]): string {
    return lastName?(firstNmae+' '+lastName+'('+restOfName.join(' ')+')'):(firstNmae+' '+'('+restOfName.join(' ')+')')
}

console.log(buildName())
console.log(buildName('Lucy'))
console.log(buildName('Lucy', 'Job'))
console.log(buildName('Lucy', 'Job', 'Yun'))

八、模块 & 命名空间

export const PI = 3
export function getValue() {
}
export interface Verifier {
}
export class Person {
}
import {Person} from './moduleA'

let person = new Person()

官网示例
Validation.ts

namespace Validation {
    export interface StringValidator {
        isAcceptable(s: string): boolean;
    }
}

LettersOnlyValidator.ts

/// <reference path="Validation.ts" />
namespace Validation {
    const lettersRegexp = /^[A-Za-z]+$/;
    export class LettersOnlyValidator implements StringValidator {
        isAcceptable(s: string) {
            return lettersRegexp.test(s);
        }
    }
}

ZipCodeValidator.ts

/// <reference path="Validation.ts" />
namespace Validation {
    const numberRegexp = /^[0-9]+$/;
    export class ZipCodeValidator implements StringValidator {
        isAcceptable(s: string) {
            return s.length === 5 && numberRegexp.test(s);
        }
    }
}

Test.ts

/// <reference path="Validation.ts" />
/// <reference path="LettersOnlyValidator.ts" />
/// <reference path="ZipCodeValidator.ts" />

// Some samples to try
let strings = ["Hello", "98052", "101"];

// Validators to use
let validators: { [s: string]: Validation.StringValidator; } = {};
validators["ZIP code"] = new Validation.ZipCodeValidator();
validators["Letters only"] = new Validation.LettersOnlyValidator();

// Show whether each string passed each validator
for (let s of strings) {
    for (let name in validators) {
        console.log(`"${ s }" - ${ validators[name].isAcceptable(s) ? "matches" : "does not match" } ${ name }`);
    }
}
上一篇下一篇

猜你喜欢

热点阅读