最详细的ts教程

112 阅读3分钟

type 和 interface 的区别

// type 可以直接定于联合类型、元组类型、基本类型 、原始值
type Size = { size: string }
type Arr = [string, number]
type Num = Number
type Name = 'a' | 'b' | 'c'

// type 能使用 in 关键字生成映射类型
type Person = {
  [key in Name]: string
}
let person: Person = { a: 'a', b: 'b', c: 'c' }

// interface 可以多次定义合并类型
interface Cat {
  name: string
  age: number
  color: string
}
interface Cat {
  onClick: (value: string) => void
}

// interface 类型可以继承
interface Height {
  height: string
}
interface User extends Height {
  age: number
}

联合类型

const data:string | number  // data拥有string和number类型

交叉类型

type Dog = { name: string; age: number; color: string }
type Cat = Dog & { id: string }

// 报错,缺少id属性
const cat1: Cat = {
  name: '小白',
  age: 2,
  color: '白色',
}

const cat2: Cat = {
  id: 'abc',
  name: '小白',
  age: 2,
  color: '白色',
}

keyof

type Dog = { name: string; age: number }

const dog: Dog = { name: '大黄', age: 3 }

const A = (key: keyof Dog) => {
  console.log(dog[key]) //读取使用类型Dog的key
}

A('name')

typeof

const data = {
  name: 'his',
  age: 22,
};

let Cat: typeof data;  // Cat  存在 name: string; age: number; 属性

Pick (选择属性)

type Dog = { name: string; age: number; color: string }

type Dog2 = Pick<Dog, 'name' | 'age'>

let dog: Dog2 // dog持有name和age类型属性

Record (属性映射)

// Record用于属性映射,类似于key value
type Dog = { name: string; age: number; color: string }

const dog: Record<string, string> = {
  a: 'a',
  b: 2,  // 报错,不能将类型“number”分配给类型“string”
}

// 配合keyof使用
const dog2: Record<keyof Dog, string> = {
  name: 'ww',
  a: 'a', // 报错,不存在a属性不能把a分配给name或age或color
}

in(映射)

// in用于联合类型对对象和数组的映射构造
type Dog = "name" | "age" | "color"

let dog: { [key in Dog]: string }  // dog持有"name" | "age" | "color"属性

Partial (不完全的)

type Dog = { name: string; age: number; color: string }

const a = (value: Dog) => {}
a({ name: 'aa', age: 3, color: 'red' }) // value内部属性必须传入

const b = (value: Partial<Dog>) => {}
b({}) // value内属性可以不传入

Required (必须的)

type Dog = { name?: string; age?: number; color?: string } // 设置非必填属性

const a = (value: Required<Dog>) => {}

a({ name: 'aa' }) //报错,缺少类型name和color

Readonly (只读)

type Dog = { name: string; age: number; color: string }

const  dog: Readonly<Dog> = {}
dog.age = 2 // age是只读属性不能分配

Exclude (排除)

// Exclude 用于联合类型
type Dog = 'namne' | 'age' | 'color'

let dog: Exclude<Dog, 'name'>

dog = 'age'

dog = 'name' // 报错,dog上不存在name

Omit (省略)

type Dog = { id:string, name: string; age: number; color: string }

const a = (value: Omit<Dog, 'name'>) => {}
//const a = (value: Omit<Dog, 'name' | 'id'>) => {} 省略多个

a({ age: 2, color: 'red' }) // name属性已经被省略

a({ age: 2, color: 'red', name: '大黄' }) // 报错,不存在name属性

// 添加函数
const add =(value:Omit<Dog,"id"> )=>{}
// 修好函数
const update =(value:Dog)=>{}

enum (枚举)

// enum默认是数字枚举,按照index下标顺序
enum Direction {
  Up,
  Down,
  Left,
  Right,
}
console.log(Direction.Up,Direction.Down);  // 输出0,1

// 按照index 2顺序
enum Direction2 {
  Up = 2,
  Down,
  Left,
  Right,
}
console.log(Direction2.Up,Direction2.Down);  // 输出2,3

// 数字枚举
enum Code {
  success = 200,
  error = 500,
}

// 字符串枚举枚举
enum Code2 {
  success = 'success',
  error = 'error',
}

获取枚举value

export enum UserRole {
  Admin = 'admin',
  Root = 'root',
  User = 'user',
}

type Roles = `${UserRole}`   //  "admin" | "root" | "user"

获取枚举key

export enum UserRole {
  Admin = 'admin',
  Root = 'root',
  User = 'user',
}

type Roles =keyof typeof UserRole  //  "Admin" | "Root" | "User"

泛型

const getData = <T>(data: T): T => {
  return data;
};

getData({name:"22"}).name

Parameters(参数)

const getData=(param:{name:string,age:number}) => console.log(param)
type P = typeof getData

// 可以拿到getData函数的入参类型
let param:Parameters<P>[0] = {name:"yyds", age:24 }

console.log(param.name)   // 输出yyds

ReturnType(返回值)

const getData = (): { name: string; age: number } => {
  return {
    name: "yq",
    age: 18,
  };
};

type T = ReturnType<typeof getData>;  // T类型就是getData函数返回的类型

Awaited (promise结果)

type P = Promise<{ name: string; age: number }>;

type T = Awaited<P>;  // T类型是{ name: string; age: number }

其他

Exclude<T, U> -- 从T中剔除可以赋值给U的类型。
Extract<T, U> -- 提取T中可以赋值给U的类型。
NonNullable<T> -- 从T中剔除nullundefinedReturnType<T> -- 获取函数返回值类型。
InstanceType<T> -- 获取构造函数类型的实例类型。