typescript-advanced-types
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript Advanced Types
TypeScript高级类型
Master TypeScript's advanced type system for building robust, type-safe applications.
掌握TypeScript的高级类型系统,构建健壮、类型安全的应用。
Generics
Generics
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 };
}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 };
}Conditional Types
Conditional Types
typescript
// 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";typescript
// 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";Mapped Types
Mapped Types
typescript
// 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]
};typescript
// 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]
};Template Literal Types
Template Literal Types
typescript
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"typescript
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"Utility Types
Utility Types
typescript
// 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 }>;typescript
// 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 Patterns
React TypeScript模式
Generic Components
泛型组件
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>
);
}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>
);
}Typed Hooks
类型化Hooks
typescript
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 };
}typescript
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 with Type Safety
带类型安全的Context
typescript
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;
}typescript
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;
}Event Handler Types
事件处理器类型
typescript
// 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);
};typescript
// 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);
};Common Event Types
常见事件类型
| Event | Type |
|---|---|
| Form submit | |
| Input change | |
| Button click | |
| Key press | |
| Focus | |
| 事件 | 类型 |
|---|---|
| 表单提交 | |
| 输入框变更 | |
| 按钮点击 | |
| 按键按下 | |
| 聚焦 | |
Ref Types
Ref类型
typescript
const inputRef = useRef<HTMLInputElement>(null);
// Forward ref
const Input = forwardRef<HTMLInputElement, InputProps>(
({ label, ...props }, ref) => (
<input ref={ref} {...props} />
)
);typescript
const inputRef = useRef<HTMLInputElement>(null);
// Forward ref
const Input = forwardRef<HTMLInputElement, InputProps>(
({ label, ...props }, ref) => (
<input ref={ref} {...props} />
)
);Children Props
Children属性
typescript
interface CardProps {
children: React.ReactNode;
title: string;
}
// Render prop
interface DataFetcherProps<T> {
url: string;
children: (data: T, loading: boolean) => React.ReactNode;
}typescript
interface CardProps {
children: React.ReactNode;
title: string;
}
// Render prop
interface DataFetcherProps<T> {
url: string;
children: (data: T, loading: boolean) => React.ReactNode;
}Type Guards
类型守卫
typescript
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");
}typescript
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");
}Best Practices
最佳实践
- Use over
unknown- Enforce type checkingany - Prefer for objects - Better error messages
interface - Use for unions - More flexible
type - Leverage inference - Let TypeScript infer when possible
- Create helper types - Build reusable utilities
- Use const assertions - Preserve literal types
- Avoid type assertions - Use guards instead
- Enable strict mode - All strict options
- 使用替代
unknown- 强制类型检查any - 对象类型优先使用- 错误提示更友好
interface - 联合类型优先使用- 灵活性更高
type - 利用类型推断 - 尽可能让TypeScript自动推断类型
- 创建辅助类型 - 构建可复用的工具类型
- 使用const断言 - 保留字面量类型
- 避免类型断言 - 优先使用类型守卫
- 启用严格模式 - 开启所有严格选项
Detailed References
详细参考资料
For comprehensive patterns, see:
- references/advanced-patterns.md
- references/type-challenges.md
如需了解完整模式,请查看:
- references/advanced-patterns.md
- references/type-challenges.md
Resources
资源
- TypeScript Handbook: https://www.typescriptlang.org/docs/handbook/
- Type Challenges: https://github.com/type-challenges/type-challenges
- TypeScript手册: https://www.typescriptlang.org/docs/handbook/
- Type Challenges: https://github.com/type-challenges/type-challenges