TypeScript打字技巧TypeScript语法类型注解
TypeScript打字技巧:掌握TypeScript语法实现更快编码
学习更快输入TypeScript代码的必备技巧。从类型注解、泛型和接口到实用类型和高级模式,提高您的TypeScript打字速度和准确性。
TypeScript已成为构建可扩展JavaScript应用程序的标准。其强大的类型系统可在编译时捕获错误,但高效输入TypeScript代码需要掌握其独特的语法模式。本综合指南将帮助您更快、更准确地输入TypeScript代码。
为什么TypeScript打字技能很重要
TypeScript在JavaScript之上添加了类型注解,这意味着需要输入更多字符。然而,早期发现错误带来的生产力提升远远超过额外的按键。能够流畅输入TypeScript的开发人员花在调试上的时间更少,而用于构建功能的时间更多。
需要掌握的TypeScript必备符号
1
冒号 (:)
用于变量、参数和返回类型之后的类型注解。
2
尖括号 (<>)
泛型、类型断言和JSX元素必不可少。
3
竖线 (|)
组合多个类型的联合类型。
4
与号 (&)
组合多个类型的交叉类型。
5
问号 (?)
可选属性和可选链。
基本类型注解模式
类型注解是TypeScript的基础。练习直到它们变得自然:
typescript
const name: string = 'Alice';
const age: number = 30;
const isActive: boolean = true;typescript
const items: string[] = ['a', 'b', 'c'];
const numbers: Array<number> = [1, 2, 3];typescript
const user: { name: string; age: number } = {
name: 'Bob',
age: 25,
};函数类型模式
TypeScript中的函数需要参数和返回类型注解:
typescript
function greet(name: string): string {
return `Hello, ${name}!`;
}typescript
const add = (a: number, b: number): number => {
return a + b;
};typescript
function fetchUser(id: number): Promise<User> {
return api.get(`/users/${id}`);
}typescript
function process(data: string, callback: (result: string) => void): void {
callback(data.toUpperCase());
}接口模式
接口定义对象的形状,是TypeScript的基础:
typescript
interface User {
id: number;
name: string;
email: string;
}typescript
interface Config {
readonly apiUrl: string;
timeout?: number;
retries: number;
}typescript
interface Repository<T> {
find(id: number): Promise<T>;
save(item: T): Promise<void>;
delete(id: number): Promise<boolean>;
}typescript
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}类型别名模式
类型别名创建自定义类型名称:
typescript
type ID = string | number;typescript
type Status = 'pending' | 'active' | 'completed';typescript
type Point = {
x: number;
y: number;
};typescript
type Callback<T> = (data: T) => void;typescript
type Nullable<T> = T | null | undefined;泛型模式
泛型实现可重用的类型安全代码:
typescript
function identity<T>(value: T): T {
return value;
}typescript
function map<T, U>(items: T[], fn: (item: T) => U): U[] {
return items.map(fn);
}typescript
class Container<T> {
constructor(private value: T) {}
getValue(): T {
return this.value;
}
}typescript
interface State<T> {
data: T;
loading: boolean;
error: Error | null;
}联合类型和交叉类型
组合类型以获得灵活性:
typescript
type StringOrNumber = string | number;typescript
type Result<T> = { success: true; data: T } | { success: false; error: string };typescript
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;typescript
function handle(value: string | number | boolean): void {
if (typeof value === 'string') {
console.log(value.toUpperCase());
}
}实用类型模式
TypeScript提供内置实用类型:
typescript
type PartialUser = Partial<User>;typescript
type RequiredConfig = Required<Config>;typescript
type ReadonlyUser = Readonly<User>;typescript
type UserKeys = keyof User;typescript
type NameType = User['name'];typescript
type UserWithoutId = Omit<User, 'id'>;typescript
type UserIdAndName = Pick<User, 'id' | 'name'>;类模式
TypeScript类支持访问修饰符和接口:
typescript
class User {
constructor(
public name: string,
private age: number,
readonly id: string
) {}
}typescript
class Service implements IService {
private cache: Map<string, Data> = new Map();
async fetch(id: string): Promise<Data> {
return this.cache.get(id) ?? await this.load(id);
}
}typescript
abstract class BaseRepository<T> {
abstract find(id: number): Promise<T>;
abstract save(item: T): Promise<void>;
}类型守卫模式
类型守卫在运行时缩小类型范围:
typescript
function isString(value: unknown): value is string {
return typeof value === 'string';
}typescript
function isUser(obj: unknown): obj is User {
return typeof obj === 'object' && obj !== null && 'name' in obj;
}typescript
if (value instanceof Date) {
console.log(value.toISOString());
}异步模式
正确类型化异步代码:
typescript
async function fetchData(): Promise<Data[]> {
const response = await fetch(url);
return response.json();
}typescript
const getData = async (): Promise<Result<User>> => {
try {
const user = await api.getUser();
return { success: true, data: user };
} catch (error) {
return { success: false, error: String(error) };
}
};React与TypeScript模式
React应用程序的常见模式:
typescript
interface Props {
title: string;
onClick: () => void;
children?: React.ReactNode;
}typescript
const Button: React.FC<Props> = ({ title, onClick }) => {
return <button onClick={onClick}>{title}</button>;
};typescript
const [count, setCount] = useState<number>(0);
const [user, setUser] = useState<User | null>(null);typescript
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value);
};模块和导入模式
组织TypeScript代码:
typescript
import type { User, Config } from './types';
import { fetchUser, saveUser } from './api';typescript
export interface ApiResponse<T> {
data: T;
status: number;
}typescript
export type { User, Config };
export { UserService, ConfigService };TypeScript练习技巧
•
专注于尖括号 <> - 它们在泛型中频繁出现
•
练习变量名后、类型前的冒号 : 位置
•
掌握联合类型的竖线 | 和交叉类型的与号 &
•
熟悉泛型约束的 extends 关键字
•
练习 keyof、typeof 和索引访问类型