关于 typescript-advanced-types
面向 TypeScript 开发者的进阶类型参考,涵盖可复用类型模式及 React 代码示例。
主要功能
- 01泛型与条件类型
- 02映射类型与模板字面量类型
- 03工具类型与类型守卫
- 04React 组件和 Hook 模式
- 05类型安全实践
适用场景
- 01用泛型建模可复用函数
- 02从现有类型构造派生类型
- 03为 React 属性、Hook 和事件添加类型
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ thapaliyabikendra/ ai-artifacts --skill typescript-advanced-types安装后在 Claude Code 中输入/typescript-advanced-types确认已加载。
详细介绍
TypeScript 高级类型
掌握 TypeScript 的高级类型系统,构建健壮、类型安全的应用程序。
泛型
// Basic generic function
function identity<T>(value: T): T {
return value;
}
// Generic with constraint
interface HasLength { length: number; }
function logLength<T extends HasLength>(item: T): T {
console.log(item.length);
return item;
}
// Multiple type parameters
function merge<T, U>(obj1: T, obj2: U): T & U {
return { ...obj1, ...obj2 };
}
条件类型
// Basic conditional
type IsString<T> = T extends string ? true : false;
// Extract return type
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
// Nested conditions
type TypeName<T> =
T extends string ? "string" :
T extends number ? "number" :
T extends boolean ? "boolean" :
"object";
映射类型
// Make all properties readonly
type Readonly<T> = { readonly [P in keyof T]: T[P] };
// Make all properties optional
type Partial<T> = { [P in keyof T]?: T[P] };
// Key remapping
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
};
// Filter by type
type PickByType<T, U> = {
[K in keyof T as T[K] extends U ? K : never]: T[K]
};
模板字面量类型
type EventName = "click" | "focus" | "blur";
type EventHandler = `on${Capitalize<EventName>}`;
// "onClick" | "onFocus" | "onBlur"
// String manipulation
type Upper = Uppercase<"hello">; // "HELLO"
type Lower = Lowercase<"HELLO">; // "hello"
type Cap = Capitalize<"john">; // "John"
工具类型
// Built-in utilities
type PartialUser = Partial<User>; // All optional
type RequiredUser = Required<PartialUser>; // All required
type ReadonlyUser = Readonly<User>; // All readonly
type NameEmail = Pick<User, "name" | "email">; // Select props
type NoPassword = Omit<User, "password">; // Remove props
type T1 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
type T2 = Extract<"a" | "b" | "c", "a" | "b">; // "a" | "b"
type T3 = NonNullable<string | null>; // string
type PageInfo = Record<"home" | "about", { title: string }>;
React TypeScript 模式
泛型组件
interface ListProps<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
keyExtractor: (item: T) => string;
}
function List<T>({ items, renderItem, keyExtractor }: ListProps<T>) {
return (
<ul>
{items.map(item => (
<li key={keyExtractor(item)}>{renderItem(item)}</li>
))}
</ul>
);
}
类型化 Hook
type ApiState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: string };
function useApiState<T>() {
const [state, setState] = useState<ApiState<T>>({ status: 'idle' });
return { state, setLoading, setSuccess, setError };
}
类型安全的 Context
interface AuthContextValue {
user: UserDto | null;
login: (credentials: LoginDto) => Promise<void>;
logout: () => void;
}
const AuthContext = createContext<AuthContextValue | null>(null);
function useAuth(): AuthContextValue {
const context = useContext(AuthContext);
if (!context) throw new Error('useAuth must be used within AuthProvider');
return context;
}
事件处理函数类型
// Form submit
const handleSubmit: React.FormEventHandler<HTMLFormElement> = (e) => {
e.preventDefault();
};
// Input change
const handleChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
console.log(e.target.value);
};
// Button click
const handleClick: React.MouseEventHandler<HTMLButtonElement> = (e) => {
console.log(e.currentTarget.name);
};
常见事件类型
| 事件 | 类型 |
|---|---|
| 表单提交 | React.FormEventHandler<HTMLFormElement> |
| 输入变更 | React.ChangeEventHandler<HTMLInputElement> |
| 按钮点击 | React.MouseEventHandler<HTMLButtonElement> |
| 按键 | React.KeyboardEventHandler<HTMLInputElement> |
| 聚焦 | React.FocusEventHandler<HTMLInputElement> |
Ref 类型
const inputRef = useRef<HTMLInputElement>(null);
// Forward ref
const Input = forwardRef<HTMLInputElement, InputProps>(
({ label, ...props }, ref) => (
<input ref={ref} {...props} />
)
);
Children 属性
interface CardProps {
children: React.ReactNode;
title: string;
}
// Render prop
interface DataFetcherProps<T> {
url: string;
children: (data: T, loading: boolean) => React.ReactNode;
}
类型守卫
function isString(value: unknown): value is string {
return typeof value === "string";
}
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== "string") throw new Error("Not a string");
}
最佳实践
- 使用
unknown而非any- 强制进行类型检查 - 对象优先使用
interface- 提供更好的错误信息 - 联合类型使用
type- 更加灵活 - 善用类型推断 - 尽可能让 TypeScript 自行推断
- 创建辅助类型 - 构建可复用的工具
- 使用 const 断言 - 保留字面量类型
- 避免类型断言 - 改用类型守卫
- 启用严格模式 - 开启所有严格选项
详细参考
如需全面的模式,请参阅:
资源
- TypeScript 手册:https://www.typescriptlang.org/docs/handbook/
- Type Challenges:https://github.com/type-challenges/type-challenges
评论
支持 Markdown