In TypeScript and JavaScript development, various punctuation symbols are not only components of syntax, but also important tools for expressing complex logic. This article will provide a detailed introduction to each symbol’s usage from basic to advanced levels, combined with practical application scenarios in the React and TanStack ecosystem.
Table of Contents
Basic Assignment and String Symbols Equal Sign = - The Art of Assignment Basic Usage
1 2 3 4 5 6 7 let userName = "Alice" ;const PI = 3.14159 ;const { data, error } = useQuery ();const [count, setCount] = useState (0 );
Advanced Applications in React
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 const [user, setUser] = useState<User | null >(null );const [state, dispatch] = useReducer (reducer, initialState);const MyComponent = ({ title, onSubmit, children }: Props ) => { return <div > {title}</div > ; };
Applications in TanStack Query
1 2 3 4 5 6 7 8 9 10 11 12 13 14 const { data : users, isLoading, error } = useQuery ({ queryKey : ['users' ], queryFn : fetchUsers, }); const mutation = useMutation ({ mutationFn : updateUser, onSuccess : (data ) => { setUser (data); }, });
Quote Family: " ' ` - Three Realms of Strings Double Quotes " and Single Quotes '
1 2 3 4 5 6 7 8 9 10 11 12 13 14 const message = "Hello World" ;const name = 'React Developer' ;<button className ="btn-primary" onClick ={handleClick} > Submit </button > const config = { "apiUrl" : "https://api.example.com" , "timeout" : 5000 };
Backticks ` - Powerful Template Strings
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 const greeting = `Hello, ${userName} !` ;const sqlQuery = ` SELECT id, name, email FROM users WHERE active = true ORDER BY created_at DESC ` ;const containerStyle = { backgroundColor : `hsl(${hue} , 70%, 50%)` , transform : `translateX(${offset} px)` }; const queryKey = ['user' , userId, `profile-${version} ` ];
Advanced Template String Usage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 const StyledButton = styled.button ` background: ${props => props.primary ? 'blue' : 'white' } ; color: ${props => props.primary ? 'white' : 'blue' } ; padding: ${({ size }) => size === 'large' ? '12px 24px' : '8px 16px' } ; ` ;const GET_USERS = gql` query GetUsers( $limit : Int! ) { users( limit : $limit ) { id name email } } ` ;
Object and Type System Symbols Colon : - Bridge Between Types and Values Object Property Definition
1 2 3 4 5 const user = { name : "张三" , age : 25 , hobbies : ["reading" , "coding" ] };
TypeScript Type Annotations
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 let count : number = 0 ;let message : string = "Hello" ;let isActive : boolean = true ;function calculateTotal (price : number , tax : number ): number { return price * (1 + tax); } interface ButtonProps { children : React .ReactNode ; variant : 'primary' | 'secondary' ; onClick : (event : React .MouseEvent <HTMLButtonElement > ) => void ; } const Button : React .FC <ButtonProps > = ({ children, variant, onClick } ) => { return ( <button className ={ `btn- ${variant }`} onClick ={onClick} > {children} </button > ); };
Complex Type Applications in TanStack
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 interface UseUserQueryOptions { userId : string ; enabled ?: boolean ; staleTime ?: number ; } const useUserQuery = ({ userId, enabled = true , staleTime = 5000 }: UseUserQueryOptions ) => { return useQuery ({ queryKey : ['user' , userId], queryFn : (): Promise <User > => fetchUser (userId), enabled, staleTime, }); }; const columns : ColumnDef <User >[] = [ { accessorKey : 'name' , header : 'Name' , cell : ({ row }: { row: Row<User> } ) => row.getValue ('name' ), }, ];
Semicolon ; - Elegant Statement Termination 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 const name = "React" ;const version = "18.0" ;const result = calculate ();[1 , 2 , 3 ].forEach (console .log ); useEffect (() => { fetchData (); }, []); const queryClient = new QueryClient ({ defaultOptions : { queries : { staleTime : 5 * 60 * 1000 , }, }, });
Bracket Family - Structure and Logic Parentheses () - Container for Functions and Expressions Function Calls and Definitions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 console .log ("Hello World" );Array .from ([1 , 2 , 3 ]);const Header = (props : HeaderProps ) => { return <h1 > {props.title}</h1 > ; }; const withAuth = (WrappedComponent : React .ComponentType ) => { return (props : any ) => { const { isAuthenticated } = useAuth (); return isAuthenticated ? <WrappedComponent {...props } /> : <Login /> ; }; };
IIFE (Immediately Invoked Function Expression)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 const module = (() => { let privateVar = 0 ; return { increment : () => ++privateVar, getCount : () => privateVar, }; })(); const ConditionalComponent = ( ) => ( <div > {(() => { if (loading) return <LoadingSpinner /> ; if (error) return <ErrorMessage error ={error} /> ; return <DataList data ={data} /> ; })()} </div > );
Square Brackets [] - Arrays and Dynamic Access Array Literals
1 2 3 4 5 6 7 8 9 10 11 const frameworks = ['React' , 'Vue' , 'Angular' ];const numbers = [1 , 2 , 3 , 4 , 5 ];const TodoList = ({ todos }: { todos: Todo[] } ) => ( <ul > {todos.map((todo, index) => ( <li key ={todo.id || index }> {todo.text}</li > ))} </ul > );
Dynamic Property Access
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 const property = 'userName' ;const value = user[property];const handleInputChange = (event : React .ChangeEvent <HTMLInputElement > ) => { const { name, value } = event.target ; setFormData (prev => ({ ...prev, [name]: value })); }; const getDynamicQuery = (filters : Record <string , any > ) => { const queryKey = ['data' , ...Object .entries (filters).map (([key, value] ) => `${key} :${value} ` )]; return useQuery ({ queryKey, queryFn : () => fetchData (filters), }); };
Index Signatures and Mapped Types in TypeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 interface StringDictionary { [key : string ]: string ; } type Partial <T> = { [P in keyof T]?: T[P]; }; type Required <T> = { [P in keyof T]-?: T[P]; }; interface UserFormProps { user : User ; onUpdate : (updates : Partial <User > ) => void ; }
Curly Braces {} - Objects and Code Blocks Object Literals and Destructuring
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 const apiConfig = { baseUrl : 'https://api.example.com' , timeout : 5000 , headers : { 'Content-Type' : 'application/json' , }, }; const { baseUrl, timeout, headers } = apiConfig;const { data, error, isLoading } = useQuery ();const { user : { name, email }, preferences : { theme } } = userProfile;
Expressions in JSX
1 2 3 4 5 6 7 8 9 10 11 12 const UserCard = ({ user, showEmail = false }: UserCardProps ) => ( <div className ="user-card" > <h3 > {user.name}</h3 > {showEmail && <p > {user.email}</p > } <div style ={{ backgroundColor: user.isActive ? 'green ' : 'gray ', padding: '10px ' }}> Status: {user.isActive ? 'Active' : 'Inactive'} </div > </div > );
Applications in TanStack Router
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 const routeTree = createRootRoute ({ component : () => ( <div > <nav > {/* Navigation component */}</nav > <main > <Outlet /> </main > </div > ), }); const userRoute = createRoute ({ getParentRoute : () => rootRoute, path : '/users/$userId' , component : ({ params }: { params: { userId: string } } ) => { const { data : user } = useQuery ({ queryKey : ['user' , params.userId ], queryFn : () => fetchUser (params.userId ), }); return user ? <UserProfile user ={user} /> : <div > Loading...</div > ; }, });
Advanced Operators and Type Symbols Question Mark ? - The Power of Optional Optional Properties and Parameters
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 interface User { id : string ; name : string ; email ?: string ; avatar ?: string ; } function createUser (name : string , email ?: string ): User { return { id : generateId (), name, ...(email && { email }), }; } interface ButtonProps { children : React .ReactNode ; variant ?: 'primary' | 'secondary' ; disabled ?: boolean ; } const Button : React .FC <ButtonProps > = ({ children, variant = 'primary' , disabled = false } ) => ( <button className ={ `btn- ${variant }`} disabled ={disabled} > {children} </button > );
Optional Chaining Operator ?.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 const userEmail = user?.profile ?.email ;const firstHobby = user?.hobbies ?.[0 ];user?.updateProfile ?.({ name : 'New Name' }); const UserProfile = ({ user }: { user?: User } ) => ( <div > <h1 > {user?.name || 'Guest'}</h1 > <p > {user?.email || 'No email provided'}</p > {user?.avatar && <img src ={user.avatar} alt ="Avatar" /> } </div > ); const UserDashboard = ( ) => { const { data : user } = useQuery ({ queryKey : ['currentUser' ], queryFn : fetchCurrentUser, }); return ( <div > <h2 > Welcome, {user?.name}!</h2 > <div > Points: {user?.gameStats?.points ?? 0}</div > </div > ); };
Ternary Operator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 const status = isOnline ? 'Online' : 'Offline' ;const LoginButton = ({ isAuthenticated, onLogin, onLogout }: Props ) => ( <button onClick ={isAuthenticated ? onLogout : onLogin }> {isAuthenticated ? 'Logout' : 'Login'} </button > ); const getStatusColor = (status : string ) => status === 'success' ? 'green' : status === 'error' ? 'red' : status === 'warning' ? 'orange' : 'gray' ; const DataComponent = ( ) => { const { data, isLoading, error } = useQuery ({ queryKey : ['data' ], queryFn : fetchData, }); return ( <div > {isLoading ? ( <LoadingSpinner /> ) : error ? ( <ErrorMessage error ={error} /> ) : ( <DataList data ={data} /> )} </div > ); };
Exclamation Mark ! - Assertion and Negation Logical NOT Operator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 const isNotActive = !user.isActive ;const isEmpty = !items.length ;const TodoItem = ({ todo, onToggle }: TodoItemProps ) => ( <div className ={!todo.completed ? 'pending ' : 'completed '}> <input type ="checkbox" checked ={!todo.completed} onChange ={() => onToggle(todo.id)} /> {todo.text} </div > );
TypeScript Non-null Assertion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 const element = document .getElementById ('root' )!;const user = getCurrentUser ()!;const MyComponent = ( ) => { const inputRef = useRef<HTMLInputElement >(null ); const focusInput = ( ) => { inputRef.current !.focus (); }; return <input ref ={inputRef} /> ; }; const users = getUsers ();const firstActiveUser = users.find (u => u.isActive )!;
Pipe | - The Wisdom of Union TypeScript Union Types
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 type Status = 'loading' | 'success' | 'error' ;type ID = string | number ;interface ButtonProps { variant : 'primary' | 'secondary' | 'danger' ; size : 'small' | 'medium' | 'large' ; children : React .ReactNode ; } type ApiResponse <T> = | { status : 'success' ; data : T } | { status : 'error' ; error : string } | { status : 'loading' }; const handleApiResponse = <T>(response : ApiResponse <T> ) => { switch (response.status ) { case 'success' : return response.data ; case 'error' : throw new Error (response.error ); case 'loading' : return null ; } };
Union Type Applications in TanStack Query
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 type QueryStatus = 'idle' | 'loading' | 'error' | 'success' ;type DataSource = | { type : 'api' ; url : string } | { type : 'cache' ; key : string } | { type : 'static' ; data : any [] }; const useDataQuery = (source : DataSource ) => { return useQuery ({ queryKey : ['data' , source.type , source.type === 'api' ? source.url : source.type === 'cache' ? source.key : 'static' ], queryFn : () => { switch (source.type ) { case 'api' : return fetch (source.url ).then (r => r.json ()); case 'cache' : return getCachedData (source.key ); case 'static' : return Promise .resolve (source.data ); } }, }); };
Ampersand & - The Power of Intersection TypeScript Intersection Types
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 type User = { name : string ; email : string };type Admin = { permissions : string [] };type AdminUser = User & Admin ;const adminUser : AdminUser = { name : 'Alice' , email : 'alice@example.com' , permissions : ['read' , 'write' , 'delete' ] }; type BaseProps = { className ?: string ; children ?: React .ReactNode ; }; type ButtonProps = BaseProps & { onClick : () => void ; variant : 'primary' | 'secondary' ; }; type LinkProps = BaseProps & { href : string ; target ?: '_blank' | '_self' ; }; const withLoading = <P extends object >(Component : React .ComponentType <P> ) => { return (props : P & { isLoading: boolean } ) => { if (props.isLoading ) { return <div > Loading...</div > ; } return <Component {...props } /> ; }; };
Arrow => - Modern Function Syntax Basic Arrow Functions
1 2 3 4 5 6 7 8 9 10 const add = (a : number , b : number ) => a + b;const greet = (name : string ) => `Hello, ${name} !` ;const processUser = (user : User ): ProcessedUser => ({ ...user, displayName : user.name .toUpperCase (), isVip : user.points > 1000 , });
Arrow Functions in React
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 const Welcome : React .FC <{ name : string }> = ({ name } ) => ( <h1 > Welcome, {name}!</h1 > ); const TodoApp = ( ) => { const [todos, setTodos] = useState<Todo []>([]); const addTodo = (text : string ) => { setTodos (prev => [...prev, { id : Date .now (), text, completed : false }]); }; const toggleTodo = (id : number ) => { setTodos (prev => prev.map (todo => todo.id === id ? { ...todo, completed : !todo.completed } : todo )); }; return ( <div > <input onKeyPress ={(e) => { if (e.key === 'Enter') { addTodo((e.target as HTMLInputElement).value); } }} /> {todos.map(todo => ( <div key ={todo.id} onClick ={() => toggleTodo(todo.id)}> {todo.text} </div > ))} </div > ); };
Applications in TanStack Query
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 const useUsers = ( ) => useQuery ({ queryKey : ['users' ], queryFn : () => fetch ('/api/users' ).then (res => res.json ()), select : (data ) => data.filter ((user : User ) => user.isActive ), }); const useCreateUser = ( ) => useMutation ({ mutationFn : (userData : CreateUserData ) => fetch ('/api/users' , { method : 'POST' , headers : { 'Content-Type' : 'application/json' }, body : JSON .stringify (userData), }).then (res => res.json ()), onSuccess : (newUser ) => { toast.success (`User ${newUser.name} created successfully!` ); }, onError : (error ) => { console .error ('Failed to create user:' , error); }, });
Modern JavaScript TypeScript Advanced Symbols Spread Operator ... - Expand and Collect Array Operations
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 const numbers = [1 , 2 , 3 ];const moreNumbers = [0 , ...numbers, 4 , 5 ];const TodoList = ( ) => { const [todos, setTodos] = useState<Todo []>([]); const addTodo = (newTodo : Todo ) => { setTodos (prev => [...prev, newTodo]); }; const removeTodo = (id : string ) => { setTodos (prev => prev.filter (todo => todo.id !== id)); }; };
Object Operations
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 const baseUser = { name : 'Alice' , age : 25 };const userWithEmail = { ...baseUser, email : 'alice@example.com' };const UserCard = (props : UserCardProps ) => ( <div {...props.divProps } className ={ `user-card ${props.divProps ?.className || ''}`}> <UserAvatar {...props.avatarProps } /> <UserInfo {...props.userProps } /> </div > ); const createQueryOptions = <T>( baseOptions : UseQueryOptions <T>, customOptions : Partial <UseQueryOptions <T>> = {} ) => ({ ...baseOptions, ...customOptions, queryKey : [...baseOptions.queryKey , ...customOptions.queryKey || []], });
Function Parameter Collection
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 const logMessages = (...messages : string [] ) => { messages.forEach (msg => console .log (msg)); }; interface FlexibleButtonProps { children : React .ReactNode ; onClick : () => void ; } const FlexibleButton = ({ children, onClick, ...restProps }: FlexibleButtonProps & React .ButtonHTMLAttributes <HTMLButtonElement > ) => ( <button onClick ={onClick} {...restProps }> {children} </button > );
Nullish Coalescing ?? and Logical Assignment Nullish Coalescing Operator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 const port = process.env .PORT ?? 3000 ; const title = user.title ?? 'Untitled' ; const UserProfile = ({ user }: { user?: User } ) => ( <div > <h1 > {user?.name ?? 'Anonymous'}</h1 > <p > Age: {user?.age ?? 'Not specified'}</p > </div > ); const useUserProfile = (userId : string ) => { return useQuery ({ queryKey : ['user' , userId], queryFn : () => fetchUser (userId), placeholderData : (previousData ) => previousData ?? getDefaultUser (), }); };
Logical Assignment Operators
1 2 3 4 5 6 7 8 9 10 11 let config : AppConfig = getConfig ();config.theme ??= 'light' ; let cache : Record <string , any > = {};cache.users ||= []; let settings : Settings = getUserSettings ();settings.notifications &&= validateNotificationSettings (settings.notifications );
Special Symbols and Modern Syntax Applications in styled-components
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 import styled, { css } from 'styled-components' ;const Button = styled.button ` padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; ${props => props.primary && css` background-color : blue; color : white; ` } ${props => props.size === 'large' && css` padding : 15px 30px ; font-size : 18px ; ` }` ;const Container = styled.div <{ width : number ; height : number }>` width: ${props => props.width} px; height: ${props => props.height} px; background: linear-gradient(45deg, ${props => props.theme.primary} , ${props => props.theme.secondary} ); ` ;
GraphQL Query Templates
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 import { gql } from '@apollo/client' ;const GET_USER_PROFILE = gql` query GetUserProfile( $userId : ID! ) { user( id : $userId ) { id name email posts { id title createdAt } } } ` ;const SEARCH_USERS = gql` query SearchUsers( $filters : UserFilters! , $pagination : PaginationInput! ) { searchUsers( filters : $filters , pagination : $pagination ) { users { ... UserFragment } totalCount hasNextPage } } fragment UserFragment on User { id name email avatar isActive } ` ;
Private Fields # Private Members in Classes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 class UserManager { #users : User [] = []; #currentUser : User | null = null ; #validateUser (user : User ): boolean { return user.name .length > 0 && user.email .includes ('@' ); } addUser (user : User ): boolean { if (this .#validateUser (user)) { this .#users.push (user); return true ; } return false ; } getCurrentUser (): User | null { return this .#currentUser; } } class DataLoader extends React.Component { #cache = new Map (); #loadingPromises = new Map (); #loadData = async (key : string ) => { if (this .#cache.has (key)) { return this .#cache.get (key); } if (this .#loadingPromises.has (key)) { return this .#loadingPromises.get (key); } const promise = fetch (`/api/data/${key} ` ).then (r => r.json ()); this .#loadingPromises.set (key, promise); try { const data = await promise; this .#cache.set (key, data); return data; } finally { this .#loadingPromises.delete (key); } }; }
Comprehensive Applications in Real Projects React TanStack Query Complete Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 interface User { id : string ; name : string ; email : string ; avatar ?: string ; isActive : boolean ; preferences : { theme : 'light' | 'dark' ; notifications : boolean ; }; } interface UserListProps { filters ?: { active ?: boolean ; search ?: string ; }; onUserSelect ?: (user : User ) => void ; } const useUsers = ({ filters }: { filters?: UserListProps['filters' ] } = {} ) => { return useQuery ({ queryKey : ['users' , filters], queryFn : async (): Promise <User []> => { const params = new URLSearchParams (); if (filters?.active !== undefined ) { params.set ('active' , filters.active .toString ()); } if (filters?.search ) { params.set ('search' , filters.search ); } const response = await fetch (`/api/users?${params} ` ); if (!response.ok ) { throw new Error ('Failed to fetch users' ); } return response.json (); }, staleTime : 5 * 60 * 1000 , enabled : true , }); }; const useUpdateUser = ( ) => { const queryClient = useQueryClient (); return useMutation ({ mutationFn : async ({ id, updates }: { id : string ; updates : Partial <User > }): Promise <User > => { const response = await fetch (`/api/users/${id} ` , { method : 'PATCH' , headers : { 'Content-Type' : 'application/json' }, body : JSON .stringify (updates), }); if (!response.ok ) { throw new Error ('Failed to update user' ); } return response.json (); }, onSuccess : (updatedUser ) => { queryClient.setQueryData ( ['users' ], (oldData : User [] | undefined ) => oldData?.map (user => user.id === updatedUser.id ? updatedUser : user ) ?? [] ); queryClient.setQueryData (['user' , updatedUser.id ], updatedUser); }, onError : (error ) => { console .error ('Update failed:' , error); }, }); }; const UserList : React .FC <UserListProps > = ({ filters, onUserSelect } ) => { const [searchTerm, setSearchTerm] = useState (filters?.search ?? '' ); const [showActiveOnly, setShowActiveOnly] = useState (filters?.active ?? false ); const debouncedSearch = useMemo ( () => debounce ((term : string ) => { }, 300 ), [] ); const queryFilters = useMemo (() => ({ active : showActiveOnly || undefined , search : searchTerm || undefined , }), [showActiveOnly, searchTerm]); const { data : users = [], isLoading, error, refetch } = useUsers ({ filters : queryFilters }); const updateUserMutation = useUpdateUser (); const handleUserToggle = useCallback ((user : User ) => { updateUserMutation.mutate ({ id : user.id , updates : { isActive : !user.isActive }, }); }, [updateUserMutation]); const handleSearchChange = useCallback ((event : React .ChangeEvent <HTMLInputElement > ) => { const value = event.target .value ; setSearchTerm (value); debouncedSearch (value); }, [debouncedSearch]); if (isLoading) { return <div className ="loading" > Loading users...</div > ; } if (error) { return ( <div className ="error" > <p > Failed to load users: {error.message}</p > <button onClick ={() => refetch()}>Retry</button > </div > ); } return ( <div className ="user-list" > <div className ="filters" > <input type ="text" placeholder ="Search users..." value ={searchTerm} onChange ={handleSearchChange} /> <label > <input type ="checkbox" checked ={showActiveOnly} onChange ={(e) => setShowActiveOnly(e.target.checked)} /> Show active only </label > </div > <div className ="users" > {users.length === 0 ? ( <p > No users found.</p > ) : ( users.map((user) => ( <UserCard key ={user.id} user ={user} onClick ={() => onUserSelect?.(user)} onToggleActive={() => handleUserToggle(user)} isUpdating={updateUserMutation.isLoading} /> )) )} </div > </div > ); }; interface UserCardProps { user : User ; onClick ?: () => void ; onToggleActive ?: () => void ; isUpdating ?: boolean ; } const UserCard : React .FC <UserCardProps > = memo (({ user, onClick, onToggleActive, isUpdating = false } ) => ( <div className ={ `user-card ${user.isActive ? 'active ' : 'inactive '}`} onClick ={onClick} > <div className ="user-info" > {user.avatar ? ( <img src ={user.avatar} alt ={ `${user.name } avatar `} className ="avatar" /> ) : ( <div className ="avatar-placeholder" > {user.name.charAt(0).toUpperCase()} </div > )} <div className ="details" > <h3 > {user.name}</h3 > <p > {user.email}</p > <div className ="preferences" > Theme: {user.preferences.theme} | Notifications: {user.preferences.notifications ? 'On' : 'Off'} </div > </div > </div > <button onClick ={(e) => { e.stopPropagation(); onToggleActive?.(); }} disabled={isUpdating} className={`toggle-button ${user.isActive ? 'deactivate' : 'activate'}`} > {isUpdating ? '...' : (user.isActive ? 'Deactivate' : 'Activate')} </button > </div > ));
Best Practices Summary Code Style Recommendations
Consistency Principle
Maintain consistent quote usage throughout the project
Uniform semicolon usage (recommended to use)
Maintain consistent indentation and line breaks
Readability First
Consider breaking complex ternary operators into if-else
Use parentheses appropriately to clarify operator precedence
Break long method chains with appropriate line breaks
Type Safety
Prioritize using TypeScript’s strict mode
Use non-null assertion ! with caution
Utilize union and intersection types to improve type precision
Object and Array Operations
Consider immutable libraries for large datasets
Avoid creating new objects in render functions
Use useMemo and useCallback judiciously
Query Optimization
Set appropriate cache times for TanStack Query
Use hierarchical structure for query keys
Avoid unnecessary duplicate requests
Error Handling
Defensive Programming
Use optional chaining to avoid null value errors
Provide reasonable default values
Handle async operation errors promptly
User Experience
Provide loading state indicators
Friendly error messages
Support retry mechanisms
Conclusion Punctuation symbols in TypeScript/JavaScript are not just syntax rules, but important tools for expressing complex logic and building modern applications. Mastering the usage of these symbols, especially their applications in React and TanStack ecosystem, helps us:
Write safer code - Avoid runtime errors through type systems and optional chaining
Improve development efficiency - Utilize modern syntax sugar and toolchains
Build maintainable applications - Clear type definitions and component structures
Optimize user experience - Through state management and data fetching optimization
Remember, tools themselves are not the goal; what matters is understanding when and how to correctly use these tools to solve real problems. In actual development, always focus on code readability, maintainability, and performance, choosing the most appropriate syntax and patterns for the current scenario.
This article covers the usage of major punctuation symbols in TypeScript/JavaScript, from basic syntax to advanced applications in modern frameworks. I hope this guide helps you better understand and utilize these powerful language features.