-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
一、普通函数的 TS 类型写法(无泛型)
核心:仅标注参数类型和返回值类型
- 函数声明式
// 格式:function 函数名(参数: 参数类型): 返回值类型 { ... }
function add(a: number, b: number): number {
return a + b;
}- 函数表达式(匿名函数)
// 格式:const 函数名 = function(参数: 参数类型): 返回值类型 { ... }
const add = function(a: number, b: number): number {
return a + b;
};- 箭头函数表达式(日常最常用)
// 格式:const 函数名 = (参数: 参数类型): 返回值类型 => { ... }
const add = (a: number, b: number): number => {
return a + b;
};二、泛型函数的 TS 类型写法
新增泛型参数 (类型占位符),参数 / 返回值可基于 T 动态定义
- 函数声明式
// 格式:function 函数名<T>(参数: 基于T的类型): 基于T的返回值类型 { ... }
// <T> 写在 function 后、函数名前
function getFirst<T>(arr: T[]): T {
return arr[0]; // 返回数组第一个元素,类型为 T
}
// 调用:可手动指定泛型,或 TS 自动推导
const num = getFirst<number>([1, 2, 3]); // num: number
const str = getFirst(["a", "b"]); // str: string(自动推导)- 函数表达式(匿名函数)
// 格式:const 函数名 = function<T>(参数: 基于T的类型): 基于T的返回值类型 { ... }
// <T> 写在 function 后、参数前
const getFirst = function<T>(arr: T[]): T {
return arr[0];
};- 箭头函数表达式(日常最常用)
// 格式:const 函数名 = <T>(参数: 基于T的类型): 基于T的返回值类型 => { ... }
// <T> 写在箭头前、参数括号外
const getFirst = <T>(arr: T[]): T => {
return arr[0];
};三、泛型 + async 函数的 TS 类型写法
- 函数声明式
// 格式:async function 函数名<T>(参数: 类型): Promise<T> { ... }
// <T> 位置和普通泛型声明式一致,返回值套 Promise
async function fetchData<T>(url: string): Promise<T> {
const res = await fetch(url);
return res.json() as T; // 断言为泛型 T,匹配返回值
}
// 调用:需用 await/.then() 接收
const user = await fetchData<User>("/api/user"); // user: User- 函数表达式(匿名函数
// 格式:const 函数名 = async function<T>(参数: 类型): Promise<T> { ... }
// <T> 写在 function 后,async 写在 function 前
const fetchData = async function<T>(url: string): Promise<T> {
const res = await fetch(url);
return res.json() as T;
};- 箭头函数表达式(日常最常用)
// 格式:const 函数名 = async <T>(参数: 类型): Promise<T> => { ... }
// <T> 写在 async 后、参数前,返回值 Promise<T>
const fetchData = async <T>(url: string): Promise<T> => {
const res = await fetch(url);
return res.json() as T;
};
// 扩展:多了联合类型参数
export const fetcher = async <T>(config: string | RequestConfig): Promise<T> => {
// 函数体逻辑
};Metadata
Metadata
Assignees
Labels
No labels