关于javascript:大前端进阶TypeScript

10次阅读

共计 3743 个字符,预计需要花费 10 分钟才能阅读完成。

概述

TypeScript 是 JavaScript 的超集,也就是说 TypeScript 不仅蕴含了 JavaScript 的全部内容,同时也蕴含其余内容。

TypeScript = JavaScript + 类型零碎 + ES6+ 新个性反对。

原始类型

TypeScript 原始类型能够和 JavaScript 根底类型一一对应。

const a: number = 1 // NaN
const b: string = 'foo'
const c: boolean = true // false
const d: void = undefined
const e: null = null
const f: undefined = undefined
const g: symbol = Symbol()

数组类型

const arr1: Array<number> = [1, 2]
const arr2: string[] = ['foo', 'bar']

元组类型

指的是明确数量和类型的数组。

const arr: [number, string] = [1, 'foo']
// 能够通过以下形式失常获取数组中的元素
console.log(arr[1])
const [num, str] = arr

object 类型

const obj: object = {}
obj['name'] = 'zhangsan'

枚举类型 enum

枚举类型指的是通过 enum 关键字定义一组键值对数据,数据定义实现后只能读取,不能批改。

// 文章状态
enum PostStatus {
    // 草稿
    Draft = 0,
    // 未公布
    Unpublished = 1,
    // 已公布
    Published = 2
}

const post = {
    title: 'typescript',
    status: PostStatus.Published
}
// 间接通过 enum 申明的枚举类型能够用数字获取枚举名称
console.log(PostStatus[0]) // Draft

常量枚举:在 enum 关键字后面加上 const

// 文章状态
const enum PostStatus {
    // 草稿
    Draft = 0,
    // 未公布
    Unpublished = 1,
    // 已公布
    Published = 2
}

// 此时再用数字获取枚举值就会报错
console.log(PostStatus[0])

函数类型

// 能够在申明函数的时候用注解的形式为参数和返回值增加类型
function sum(a: number, b: number): number {return a + b}
// 也能够用箭头函数示意函数类型
const sum1: (a: number, b: number) => number
    = function (a, b) {return a + b}
// 函数申明后,调用时只能传入与申明绝对应的参数类型和参数数量
// 或者应用可选参数和残余参数
function test(a?: number, ...rest: number[]) {// todo}

任意类型

ts 中能够应用 any 示意任意类型,提供 any 次要是为了兼容老的 js 代码。

let a: any = 1
// 能够扭转 a 的类型
a = 'foo'

类型推断

当未扭转量指明类型的时候,ts 能够通过参数值推断参数类型。

// 此时会主动推断 a 的类型为 number
const a = 1

类型断言

ts 中能够手动指定变量的类型。

const a: number | undefined = undefined
// 将 a 的类型转为指定为 number
let b: number = a as number
let c: number = <number>a

接口

能够通过 interface 关键字设置对象必须满足某种要求。

const enum PostStatus {
    // 草稿
    Draft = 0,
    // 未公布
    Unpublished = 1,
    // 已公布
    Published = 2
}
// 要求文章必须具备 title,status, id 属性,能够有 subtitle 属性,其中 id 为只读属性
interface Post {
    title: string
    subtitle?: string
    status: PostStatus,
    readonly id: number
}
let obj: Post = {
    title: 'typescript',
    status: PostStatus.Draft,
    id: 1
}
// 只读属性不能批改
obj.id = 2

针对 cache 这种属性不确定的对象,能够应用动静成员。

interface ICache {
    // 要求属性和属性值均为字符串
    [key: string]: string
}

let cache: ICache = {}
// 能够在应用的时候给对象增加符合要求的属性
cache['foo'] = 'bar'

TypeScript 在 ES2015 的 class 类根底上增加了一些关键字,用于形容类的类型。

class Person {
    name: string
    // 公有属性,内部无奈访, 能够增加 readonly 使其变为只读属性
    private readonly type: string = 'person'
    // protected 受爱护,只能在外部和子类外部应用
    protected field: string = 'foo'
    constructor(name: string) {this.name = name}

    sayHi(msg: string) {
        // 能够在类外部拜访公有属性
        console.log(`my name is ${this.name}, i am a ${this.type}, ${msg}`)
    }
}

class Student extends Person {constructor(name: string) {super(name)
    }

    sayHi() {
        // 能拜访父类受爱护的属性,然而不能拜访公有 private 属性
        console.log(this.field)
    }
}

当 privite 用在 constructor 后面时,那么这个类就不能在其余中央应用 new 生成实例。

class Book {
    title: string;
    private constructor(title: string) {this.title = title}
    // 可通过静态方法提供实例化对象的路径
    static create(title: string) {return new Book(title)
    }
}
const ts = Book.create('TypeScript')

同时,类能够继承接口,示意类须要具备某些办法或者属性。

interface IBook {getContent(): string
}

// 类能够继承多个接口
class Book implements IBook {
    title: string;
    constructor(title: string) {this.title = title}
    // 必须实现接口
    getContent(): string {return `TypeScript is a Language`}
}

抽象类

抽象类申明和一般类类似,只不过抽象类不能实例化,同时抽象类中的形象办法须要子类实现。

abstract class Person {
    name: string;
    // 形象属性
    abstract field: string
    constructor(name: string) {this.name = name}
    // 形象办法
    abstract sayHi(msg: string): void
}

class Student extends Person {
    field: string = 'test';
    sayHi(msg: string): void {console.log(msg)
    }
}

泛型

泛型能够了解为 将可变动的类型当作一个参数

const createNumberArray = function(length: number, value: number): number[] {return Array(length).fill(value)
}
const arr = createNumberArray(2, 1) // [1, 1]

const createStringArray = function(length: number, value: string): string[] {return Array(length).fill(value)
}
const arr1 = createStringArray(2, 'foo') // [foo, foo]

在下面的例子中,createNumberArray 和 createStringArray 除了参数和返回值的类型不同之外,其余都一样,此时就能够应用范型。

function createArray<T>(length: number, value: T): T[] {return Array(length).fill(value)
}
// 在应用时指定类型
const arr = createArray<number>(2, 1) // [1, 1]
const arr1 = createArray<string>(2, 'foo') // [foo, foo]

类型申明 declare

import {camelCase} from 'lodash'
// 当援用相似 lodash 这种没有类型申明文件的第三方库时,如果不明确申明引入的变量的类型,将会报错
declare let camelCase = (str?: string) => string
console.log(camelCase('hello typescript'))

通常类型申明会放入 *.d.ts 文件中

正文完
 0