TypeScript 本身基于 JavaScript,因此 JavaScript 的内置函数(方法)在 TypeScript 中同样适用,同时 TypeScript 新增了一些类型相关的工具函数(用于类型操作)。以下是常用的内置函数分类整理:
一、JavaScript 原生内置函数(TypeScript 通用)
这些是 JS 内置对象的方法,在 TS 中可直接使用,且 TS 会提供类型校验。
1. 数组(Array)相关
- Array.isArray(value) :判断值是否为数组。
Array.isArray([1, 2]); // true
Array.isArray("123"); // false
array.map(callback) :遍历数组,返回新数组(有回调函数返回值组成)。
array.filter(callback) :筛选数组元素,返回符合条件的新数组。
array.reduce(callback, initialValue) :累加/合并数组元素,返回最终结果。
array.find(callback) :返回第一个符合条件的元素。
array.includes(value) :判断数组是否包含指定值(返回布尔值)。
array.join(separator) :将数组元素拼接为字符串。
2.字符串(string)相关
- String.fromCharCode(num1,num2...) :将Unicode编码转为字符串。
String.fromCharCode(65); // "A"
str.includes(substr) :判断字符串是否包含字串。
str.indexOf(substr) :返回字串首次出现的索引(未找到返回-1)。
str.split(separator) :将字符串分割为数组。
str.trim() :去除字符串首尾空白。
str.toUpperCase / toLowerCase() :转换大小写。
3.数字(Number)相关
- Number.isNaN(value) :判断值是否为 NaN (更准确,避免 isNaN 的类型转换问题)。
Number.isNaN(NaN); // true
Number.isNaN("NaN"); // false(字符串不会被转换)
Number.parseInt(str, radix) :解析字符串为整数(指定基数,如10为十进制)。
Number.parseFloat(str) :解析字符串为浮点数。
num.toFixed(diagits) :将数字转为指定小数位数的字符串。
4.对象(Object)相关
Object.keys(obj) :返回对象自身可枚举属性的键名数组。
Object.values(obj) :返回对象自身可枚举属性的键值数组。
Object.entries(ob) :返回对象可枚举属性的 [key, value] 数组。
Object.assign(target, ...sources) :合并对象(浅拷贝)。
5.其他常用
JSON.parse(str) :将 JSON 字符串解析为对象。
JSON.stringify(obj) :将对象转为 JSON 字符串。
setTimeout(callback, delay) :延迟执行函数。
clearTimeout(timerId) :取消延迟执行。
console.log / console.error 等:控制台输出。
二、TypeScript类型工具函数(仅用于类型操作)
这些是TS提供的类型层面的工具函数,用于处理类型(编译器生效)。
1.常用基础工具类型
- Partial<T> :将 T 所有属性转为可选。
interface User { name: string; age: number }
type PartialUser = Partial; // { name?: string; age?: number }
Required<T> :将 T 所有属性转为必选(与 Partial 相反)。
Readonly<T> :将 T 所有属性转为只读。
Pick<T, K> :从 T 中选取指定属性 K 组成新类型。
type PickUser = Pick; // { name: string }
Omit<T, K> :从 T 中排除指定属性 K 组成新类型(与Pick相反)。
Exclude<T, U> :从 T 中排除可分配给 U 的类型。
type E = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
Exclude<T, U> :从 T 中提取可分配给 U 的类型(与 Exclude 相反)。
ReturnType<T> :获取函数 T 的返回值类型。
type Fn = () => number;
type Return = ReturnType; // number
2.其他工具类型
- Record<K, T> :定义一个键为 K 类型、值为 T 类型的对象类型。
type Dict = Record; // { [key: string]: number }
- Parameters<T> :获取函数 T 的参数类型组成的元组。
type Fn = (a: number, b: string) => void;
type Params = Parameters; // [number, string]
浙公网安备 33010602011771号