TypeScript Type System in Practice: From Basics to Advanced Utility Types
前端工程(Updated May 24, 2026)
Why Does a Tool Site Need TypeScript?
ToolsKu has 200+ tool pages, 4-language i18n, and complex tool client configuration. Pure JavaScript is error-prone in these scenarios:
- Typos in tool config object fields
- Missing i18n keys with no compile-time warning
- API response shapes that don't match expectations
- Missed reference updates during refactors
TypeScript catches these errors at compile time, not runtime.
Core Type Techniques
1. Type Inference vs Explicit Annotations
// ✅ Let TS infer (concise)
const tools = [{ href: '/pdf/merge', name: 'PDF合并' }] as const;
// ✅ Explicit annotation when constraints are needed
function getTool(href: string): ToolItem | undefined {
return ALL_TOOLS.find(t => t.href === href);
}
2. Generic Constraints
function encode<T extends string | ArrayBuffer>(
input: T
): T extends string ? string : ArrayBuffer {
// Return different results based on input type
}
3. Union Types and Type Guards
type ProcessResult =
| { status: 'success'; data: Blob }
| { status: 'error'; message: string };
function handleResult(result: ProcessResult) {
if (result.status === 'success') {
downloadBlob(result.data); // TS knows data exists
}
}
Advanced Utility Types
Partial, Required, Pick, Omit
type ToolConfig = {
href: string;
name: string;
blurb: string;
i18nKey?: string;
};
type ToolUpdate = Partial<ToolConfig>; // all fields optional
type ToolRequired = Required<ToolConfig>; // all fields required
type ToolPreview = Pick<ToolConfig, 'name' | 'blurb'>; // pick subset
Conditional Types
type IsString<T> = T extends string ? true : false;
type A = IsString<'hello'>; // true
type B = IsString<42>; // false
Mapped Types
type Readonly<T> = { readonly [K in keyof T]: T[K] };
type Nullable<T> = { [K in keyof T]: T[K] | null };
JSON → TypeScript Generation
How ToolsKu's JSON to TypeScript tool works:
function jsonToTypeScript(json: unknown, name = 'Root'): string {
if (Array.isArray(json)) {
return `${name}[]`;
}
if (typeof json === 'object' && json !== null) {
const fields = Object.entries(json).map(([key, value]) => {
const type = jsonToTypeScript(value, capitalize(key));
return ` ${key}: ${type};`;
});
return `interface ${name} {\n${fields.join('\n')}\n}`;
}
return typeof json; // string | number | boolean
}
Paste an API response JSON and generate a TypeScript interface in one click—cutting down manual type authoring.
Practical Patterns
satisfies Operator (TS 4.9+)
const config = {
locales: ['zh-CN', 'en'],
defaultLocale: 'zh-CN',
} satisfies RoutingConfig; // keeps literal types while validating structure
const Type Parameters (TS 5.0+)
function createTool<const T extends string>(href: T) {
return { href } as const;
}
const tool = createTool('/pdf/merge'); // href type is '/pdf/merge', not string
Summary
TypeScript's type system is more than "adding type annotations"—it's a compile-time programming language. Mastering generics, conditional types, and utility types builds self-documenting, refactor-safe codebases. ToolsKu's JSON to TypeScript tool is a practical starting point for type-driven development.
Try these browser-local tools — no sign-up required →
#TypeScript#类型系统#泛型#工具类型#工程化