Hibop.github.io icon indicating copy to clipboard operation
Hibop.github.io copied to clipboard

Typscript朝花夕拾~~

Open Hibop opened this issue 11 months ago • 0 comments

命令行转换

tsc --target es6 test.ts

常用静态类型

number、string、boolean、array、tuple、enum

类型别名 (Type Aliases)

type StringOrNumber = string | number;
let value: StringOrNumber = 42;

枚举 (Enums)

元组(Tuples)

数组中元素的数据类型都一般是相同 number[]; 如果存储的元素数据类型不同,则需要使用元组 元组允许定义具有固定数量和类型的数组。它适用于需要固定数据结构的场景,比如坐标或 RGB 颜色值。

let point: [number, number] = [10, 20];

注意和不定类型数组区别: (string | number)[]

泛型

参数化类型,运行时类型指定

function identity<T>(value: T): T {
  return value;
}

let num = identity<number>(42);

工具类型

Partial、Pick、Readonly、Record, Omit 等,这些类型可以帮助生成新的类型,简化类型定义。

  • Partial<T>: 将T中的所有属性设置为可选 name?:string 【name-?: string】必须
  • Pick<Type, Keys>: 获得特定屬性
  • Omit<Type, Keys>: 省略特定屬性
  • Record<Keys, Type> *最常使用Record<string, any>
  • ReturnType<IFunc> 函数返回值
interface ITodo {
  title: string,
  description: string,
  id: number,
}

let partialTodo: Partial<ITodo > = { title: "Learn TypeScript" }; // 可选属性
type IPick = Pick<ITodo, ‘id’ | 'title'>;

keyof & in 遍历 & typeof

keyof 获取类型内所有的 key,即所有属性名 , 获取的是一个 联合类型

  interface IPeople {
    name:string,
    age?: number,
    sex: string,
  }
  
  type T = keyof IPeople

  // 等同于
  type T = "name" | "age" | "sex"

  type TAny = keyof any
  // 等同于
  type TAny = string | number | symbol //不包括 boolean object等

一些实战

// 1 对象
  const people = {
    name: "liuyz",
    age: 20,
    info: {
      sex: "man",
      hobby: "sleep",
    }
   }
  
  type IPeople = typeof people
  // 等同于
  // type IPeople = {
  //   name: string
  //   age: number
  //   info: {
  //     sex: string
  //     hobby: string
  //   }
  // }
  
  type IPeople = keyof typeof people  // keyof 只会获取数据类型的第一级属性key
  // 等同于
  // type IPeople = "name" | "age" | "info"

// 2  函数
  const add = (a: number, b: number): number => {
    return a + b
  }
  
  type TFunType = typeof add // 获取函数类型
  // 等同于
  // type TFunType = (a: number, b: number) => number
  type TReturnType = ReturnType<TFunType> // 获取函数返回值类型
  // 等同于
  // type TReturnType = number
  type TParamsType = Parameters<TFunType> // 获取函数参数类型,转变为元组类型
  // 等同于
  // type TParamsType = [a: number, b: number] // 元组类型

// 3 数组

Hibop avatar Jan 27 '25 03:01 Hibop