介绍

声明并赋值

  • 布尔值
  • 数字
  • 字符串
  • 数组
  • 元组 Tuple
  • 枚举
  • any
  • void
  • Null
  • Undefined
  • Never
  • Object ```typescript // 布尔值 let isDone: boolean = false;

// 数字 let decLiteral: number = 6; let hexLiteral: number = 0xf00d; let binaryLiteral: number = 0b1010; let octalLiteral: number = 0o744;

// 字符串 let name: string = “bob”; name = “smith”;

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

// 枚举 // 常量枚举 const enum

// 函数类型 // 设置可选参数: ?, 以下 b 为可选参数, c 设置了默认值, rest为解构 function func1(a: number, b?: number, c: number = 1, …rest: number[]): string { return ‘func1’ }

// 任意类型 // Any

// 断言,是明确告诉 ts 数据的类型,有时候 ts 无法推断出数据类型(非类型转换,只在编译的时候时候) const num1 = res as number

// 接口 interface Post { title: string content: string }

function printPost (post: Post) {}

// 接口补充 // 可选成员, 用 ? 标识 interface Post { title: string content?: string }

//只读成员, 初始化后就不能再修改. interface Post { title: string readonly content: string }

// 动态成员(成员总数不限,但是他们的类型都需要是 string 类型), interface Post {

}

const cache: Post = {}

cache.foo = ‘aaaa’ cache.bar = ‘bbbb’ cache.wq = ‘cccc’

// class 类, 用来描述一类具体对象的抽象成员 // class Person { public name: string // 默认就是 public, private age: number // 必须在构造函数中赋值 , private, 私有成员. protected readonly gender: boolean // 允许子类访问 constructor(name: string, age: number){ this.name = name this.age = age }

sayHi(): void { } }

class Student extends Person { constructor (name: string, age: number){ super(name,age) console.log(this.gender) } }

// 类的只读属性 // readonly

// 接口 // 类与类之间共同的特性, 都能跑,但是跑的方式不一样. interface Eat{ eat (food:string): void }

// 接口2 interface Run{ run (distance: number): vold }

class Person implements Eat,Run { eat (food: string): void {

} run (distance: number): void { } }

// 抽象类, 只能被继承,不能直接使用 abstract class Animal { eat (food: string): void { } // 抽象方法 abstract run (distance: number): void { } }

class Dog extends Animal { run (distance: number): void { } }

const d = new Dog() d.eat(‘cook’) d.run(100)

// 泛型, 定义的时候不指定具体的类型,在使用的时候来指定类型 // 在函数末尾添加, function createNumberArray(length: number, value: number): number[] { const arr = Array(length).fill(value) return arr }

function createArray (length: number, value: T): T[] { const arr = Array(length).fill(value) }

const res = createArray(3, ‘foo’)

// 类型声明, 安装类型声明模块 import { camelCase } from ‘lodash’

declare function camelCase (input: string): string

const res = camelCase(‘hello typed’)

// ————— import { camelCase } from ‘lodash’ import qs from ‘query-string’ // 安装对应的类型声明模块( @types/lodash ) qs.parse(‘?key=value&key2=value2’)

// declare function camelCase (input: string): string

const res = camelCase(‘hello typed’)

```