TypeScript -- javaScript超集

46 阅读4分钟

前言

回顾下TS基础知识

1. 快速上手

yarn init 
yarn add typescript  
​
// 01-getting_start.ts
const hello = name: string => {
    console.log(`name is ${name}`)
}
// yarn tsc 01-getting_started  => 会生成 01-getting_start.js 文件 (移除了声明 注解 并转换为 ES3)

2. 配置文件

 yarn tsc --init  //生成配置文件 target: es5  module: 'commonjs'  outDir: 'dist'  rootDir: 'src'  sourceMap:'true'  strict: 'true'
 
 yarn tsc //更改配置后需要编译整个项目才会生效

3. 原始数据类型

const a: string = 'a' 
const b: number = 100 // NaN Infinity
const c: boolean = true // false// const d: boolean = null  strict模式下会报错
const e: void = undefined
const f: null = null
const g: undefined = undefined
const h: symbol = Symbol() // 报错

4. 标准库声明

const h: symbol = Symbol() // 报错
// 配置文件中 'lib': ['Es2015', 'Dom']

5. 中文错误消息

// 01
yarn tsc --local zh-cn
​
// 02
vscode => typescript local => zh-cn

6. 作用域问题

// 01.ts
const a: string = 'a'// 02.ts
const a: number = 100 //报错 重复定义//解决方案
// 01
(function(){
    const a = 23
})()
// 02
export {} // 使用moduel 语法 使其具有单独作用域

7. Object类型

export {} // 确保无成员冲突
// object 泛指六个基本类型外的类型
const foo: object = function () {} // []
const obj: { foo: number, bar: string } = { foo: 18, bar: 'bar' }

8. 数组类型

const arr1: Array<number> = [1,2,3]
const arr2: number[] = [1,2,3]
​
function sum(...args: number[]){    
    return args.reduce((prev,current)=> prev + current,0)
}
sum(1,2,3,4)

9. 元组类型

//固定长度和类型的数组
export {} // 确保无成员冲突
const tuple: [number, string] = [18, 'zac']
const [age, name] = tuple
// 元组一般用于 返回值
Object.entries({
    foo: 123,
    bar: 456
})

10. 枚举类型

​
export {} // 确保没有成员冲突
//常用模拟状态
const PostStaus = {
    Draft: ',
    Unpublished: 1,
    Published: 2
} 
// 使用枚举
enum PostStatus = {
    Draft = 0,
    Unpublishe = 1,
    Published = 2
}
// 默认从0累加
enum PostStatus = {
    Draft,
    Unpublishe,
    Published
}
enum PostStatus = {
    Draft = 6,
    Unpublishe,
    Published
}
// 非数字需全部指定
enum PostStatus = {
    Draft = 'aa',
    Unpublishe = 'bb',
    Published = 'cc'
}
​
const post = {
    status: PostStatus.Draft
}
​
// 枚举类型会入侵 不会像其他类型声明被移除 会编译成双向键值对对象(如图1), 可使有常量枚举
const enum PostStatus = {
    Draft = 'aa',
    Unpublishe = 'bb',
    Published = 'cc'
}
​
​

11. 函数类型

export {} // 确保无成员冲突
// 可选参数 不定参数 需放在最后
//function func1 (a:number, b?:number): string {
//function func1 (a:number, b:number, ...rest: number[]): string {function func1 (a:number, b:number): string {
    return 'func1'
}
  func1(100 , 200)
  func1(100 , 200, 300) // 报错 // 表达式
cosnt func2: (a:number, b:number) => string = function(a:number,b:number):string{ 
return 'func2'
}
​

12. 任意类型

export {} // 确保无成员冲突
function stringfy (value: any){
    return JSON.stringfy(value)
}
stringfy('string')
stringfy(100)
let foo: any = 'string'
foo = 100
foo.bar()
// any 不安全

13. 隐式类型推断

​
export {} // 确保无成员冲突
let age = 18 // 推断为 age: number
// age = 'a' 报错
let foo // 推断为 foo: any
foo = 100
foo = 'f'

14. 类型断言

export {} // 确保无成员冲突
const nums = [1,2,3,4,5,6]
const res = nums.find(i => i > 0)
​
// const square = res * res
const num1 = res as number
const num2 = <number>res // jsx 下不能使用

15. 接口

​
export {} // 确保无成员冲突interface Post {
    title: string
    content: string
    subtitle?: string  // 可选
    readonly summary: string // 只读
}
​
function printPost (post: Post) {
    consoel.log(post.title)
    consoel.log(post.content)
}
​
printPost({
    itle: 'title'
    content: 'content'
})
// ------------
interface Post {
    title: string
    content: string
    subtitle?: string  // 可选
    readonly summary: string // 只读
}
const hello: Post = {
    title: 'title'
    content: 'content'
    summary: 'summary'
}
hello.summary = 'aa'  // 报错// 动态成员
interface  Cache = {
    [prop: string] =  string
}
const cache: Cache = {}
cache.foo = 'foo'
cache.bar = 'bar'

16. 类

// typescript 对 class 做了增强
class Person {
    name:string  // = 'init name'
    private age: number
    protected gender: boolean
    constructor(name: string, age: number){
        this.name = name
        this.age = age
        this.gender = gender
    }
    sayHi (msg: string ): void{
        console.log(this.name + msg)
    }
}
//访问修饰符 private(无法继承) public(默认) protected(只能由子类访问)
const tom = new Person('tom', 18)
console.log(tom.name)
console.log(tom.age) //报错
console.log(tom.gender) // 报错
class Student extends Person {
    private constructor(name: string, age: number){
        super(name, age)
        console.log(this.gender)
    }
    
    static create (name: string, age:number){
        return new Student(name, age)
    }
}
​
// const jack = new Student('jack', 18) // 报错
const jack = new Student('jack', 18) 
//  只读属性 readonly---
// 必须初始化 且无法更改
class Person {
    name:string  // = 'init name'
    private age: number
    protected readony gender: boolean
    constructor(name: string, age: number){
        this.name = name
        this.age = age
        this.gender = true
    }
    sayHi (msg: string ): void{
        console.log(this.name + msg)
    }
}
const tom = new Person('tom', 18)
tom.gender = false // 报错

17. 类与接口

export {} // 确保无成员冲突interface Eat {
    eat (foo:string) : void
}
interface Run {
    run (distance: number) : void
}
​
class Person implements Eat, Run {
    eat (food : string): void {
        console.log('优雅的吃', food)
    }
    
    run (distance: number): void {
        console.log('直立行走', distance)
    }
}
​
class Animal implements Eat, Run {
    eat (food : string): void {
        console.log('进食', food)
    }
    
    run (distance: number): void {
        console.log('爬', distance)
    }
}
​

18. 抽象类

export {} // 确保无成员冲突
// 抽象类只能被继承 无法实例化
abstract class Animal implements Eat, Run {
    eat (food : string): void {
        console.log('进食', food)
    }
    
    abstract run (distance: number): void {
        console.log('爬', distance)
    }
}
​
class Dog extends Animal {
    run(distance: number): void{
        console.log('狗在跑', distance)
    }
}
​
const d = new Dog()
d.eat('apple')
d.run(100)
​

19. 泛型

// 声明不指定类型 使用时再指定 不明确类型 可使用参数
function creatNumberArray(length: number, value: number): number[]{
    const arr = Array(length).fill(value)
    return arr
}
​
function creatStringArray(length: number, value: string): string[]{
    const arr = Array<String>(length).fill(value)
    return arr
}
​
function creatArray<T>(length: number, value: T): T[]{
    const arr = Array<T>(length).fill(value)
    return arr
}
​
const res = createArray<string>(18,'food')
​