Type safety keeps values within operations permitted by their types, helping TypeScript catch invalid use before it becomes a runtime failure. It supports maintainable, scalable code by enforcing contracts around APIs, functions, components, and external JavaScript. section 3.7 section 3.9
Interview-ready practices include:
- Prefer unknown over any for uncertain values: unknown requires narrowing before operations, while any disables type checking. section 3.7
- Use type narrowing with typeof, instanceof, control flow, user-defined guards, and discriminated unions. section 3.9
- Use generics to preserve type information across reusable functions, classes, and React components instead of bypassing checks with any. section 3.8
- Enable strict compiler settings, reduce unsafe assertions, and supply declaration files or global augmentation when JavaScript APIs lack types. section 3.9 section 3.10
Typing an asynchronous YouTube API
A React component loads the YouTube script and accesses window.YT and window.onYouTubeIframeAPIReady. TypeScript reports missing global properties and an implicitly typed event. Extending the global Window interface declares the API shape; alternatively, @types/youtube supplies library types while a small global declaration covers the callback. The result preserves static checking across the JavaScript boundary. section 3.10
Listing 3.15 Generic List component
interface ListProps<T> { #A
items: T[]; #B
renderItem: (item: T) => JSX.Element; #C
}
const List = <T,>({ items, renderItem }: ListProps<T>) => (
<ul>{items.map(renderItem)}</ul>
);
// Usage of the generic List component
interface User {
id: number;
name: string;
}
const users: User[] = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
const renderUser = (user: User) => <li key={user.id}>{user.name}</li>; #D
<List<User> items={users} renderItem={renderUser} /> #E
Browse a generic React List whose item type flows from its props into renderItem, demonstrating reusable type safety without any. section 3.8










