TypeScript Flashcards
TypeScript Basics (23 cards)
How has TypeScript improved your development workflow?
- Catching errors early
- Enhancing IDE experience
- Self-documenting code
- Safer refactoring
- Better team collaboration
- Improved maintainability
TypeScript helps in identifying issues at compile time and enhances code readability and collaboration among team members.
What are the benefits of using interfaces vs. types in TypeScript?
Both interfaces and types have their place in TypeScript:
Interfaces:
* Can be extended with the extends keyword
* Can be implemented by classes with implements
* Support declaration merging
* Better for defining object shapes in OOP paradigms
* Preferred for public API definitions
Types:
* More flexible and can represent unions, primitives, tuples
* Support mapped types for transforming existing types
* Can use advanced type manipulations like conditional types
* Better for functional programming patterns
* Support computed properties with literal types
Interfaces are often favored for object-oriented programming, while types are better for functional patterns.
How do you approach typing complex data structures in TypeScript?
When typing complex data structures, I follow these principles:
* Start with composition of simple types
* Use generics for reusable container types
* Leverage discriminated unions for different variants
* Index signatures for dynamic properties
* Utilize utility types (Partial, Omit, Pick) for derived types
* Module augmentation for extending external libraries
These principles help maintain type safety and reusability across complex data structures.
When and why would you use generic types in TypeScript?
I use generic types when I need to create reusable components, functions, or data structures that work with various data types while maintaining type safety. The main scenarios include:
* Creating type-safe containers
* Writing utility functions that work across types
* Typed API response handlers
* Component props in React
* State management with type safety
Generics help in writing reusable code that maintains type safety and reduces duplication.
How do you create reusable typed components in React with TypeScript?
Creating reusable typed components involves several key patterns:
* Use generics for flexible prop types
* Component composition with children
* Render props pattern with TypeScript
* Higher-order components with TypeScript
* Prop spreading with TypeScript
These patterns allow for enhanced flexibility and reusability in component design.
How do you handle type narrowing in TypeScript?
Type narrowing is essential for handling complex types and unions. Techniques include:
* typeof type guards for primitive types
* instanceof checks for class instances
* Property presence checks
* Discriminated unions
* User-defined type guards for complex scenarios
* Assertion functions in TypeScript 3.7+
These techniques allow for more precise type checking and handling in complex scenarios.
When would you use type assertions and what are the risks?
I use type assertions in scenarios such as:
* Integrating with untyped third-party libraries
* Working with DOM elements
* When I have more information than the compiler
* For complex type transformations
Risks include:
* Hiding type errors
* Runtime errors
* Breaking type safety
* Propagating incorrect types
To mitigate these risks, I prefer type guards and narrowing when possible.
How do you type props, state, and event handlers in React components?
For typing React components:
* Props typing using interfaces
* State typing with useState
* Event handlers with specific event types
This ensures that components are type-safe and maintainable.
What is your approach to typing higher-order components in React?
For typing higher-order components (HOCs):
* Use generic HOC with inference
* HOC that adds props
* HOC with props mapping
* Forwarding refs in HOCs
This maintains type safety while enhancing component functionality.
How do you handle typing for hooks in TypeScript?
For typing hooks:
* Basic custom hook with TypeScript
* Using generics for more complex hooks
This ensures that hooks are reusable and type-safe.
What is the purpose of the trackClick function?
Tracking logic
The function is intended to handle click tracking for a component.
How do you define a basic custom hook in TypeScript?
function useCounter(initialValue: number = 0) { … }
A basic custom hook can be defined using useState to manage local state.
What does the useCounter hook return?
It returns an object with count, increment, decrement, and reset
These methods allow manipulation of the count value.
What is the purpose of the useLocalStorage hook?
To manage local storage with a specified key and initial value
This hook provides a way to sync state with local storage.
What parameters does the useLocalStorage hook take?
key: string, initialValue: T
The key is the local storage key, and initialValue is the default state.
What does the setValue function in useLocalStorage do?
Sets the value in both state and local storage
It accepts a new value or a function to compute the new value.
What is the interface UseApiResult used for?
To define the structure of the result returned by useApi hook
It includes data, loading, error, and refetch properties.
What does the fetchData function in useApi do?
Fetches data from a specified URL and handles loading and error states
It updates the state based on the API response.
What happens if the response from the API is not ok in useApi?
An error is thrown with the status of the response
This is handled in the catch block of fetchData.
What does the useEffect hook do in the context of useApi?
Calls fetchData whenever the URL changes
It ensures the data is fetched when the component mounts or the URL updates.
What is the purpose of createApiHook?
To create a reusable API hook with TypeScript
It allows for parameterized API calls.
What type parameters does createApiHook accept?
TParams, TResult
TParams defines the parameters for the API call, and TResult defines the expected result type.
How can you use the createApiHook function?
const useUsers = createApiHook<{page: number}, User[]>(…)
This creates a specific API hook for fetching users with pagination.