Type Safety
28 bites tagged Type Safety — interview questions with model answers, and 60-second explainers.
Compile-time vs runtime prop validation across frameworks?
TypeScript (compile-time) catches errors before build; Vue props validation (runtime) catches at runtime; tradeoff: TS is stricter, Vue validation is flexible but less safe. understanding of type safety mechanisms.
CodeGen and Typed Scaffolding in the New Architecture
It reads typed JS specs and generates native interfaces at build time so JS and native agree on types, avoiding runtime checks and giving compile-time safety. CodeGen's purpose.
Type-safe navigation with TypeScript
Define a ParamList mapping screen names to param types, type Screen via NativeStackScreenProps, and type useNavigation with the navigation prop generic so route names and params autocomplete. typing navigation.
Go (T, error) versus Rust Result for error handling
Go returns a separate error value you may ignore; Rust wraps success or error in one Result enum the compiler forces you to handle. Go favors simplicity, Rust favors compile-enforced safety. understanding of explicit error models.
Fearless concurrency: Rust compile-time vs Go runtime
Rust uses ownership plus Send/Sync to reject data races at compile time; Go encourages channels but still allows races, with the runtime race detector catching them at test… understanding of where each language catches concurrency bugs.
What is tsconfig strict, and which sub-flag to relax for legacy?
Tests strict as a master switch and migration pragmatism. Strong answers name strictNullChecks or noImplicitAny as the first to relax in legacy code, trading null-safety for fewer errors. Red flag: disabling strict entirely instead of a targeted sub-flag.
Design a type-safe generic localStorage wrapper in TypeScript
Generic getItem<T> returns T|null via JSON.parse, setItem<T> stringifies, and a key-to-type map enforces safety. Preserving compile-time types across localStorage's string-only API.
Write a generic fetchJSON<T> wrapper and explain its type safety benefits
Tests preserving type info across async boundaries via generics. Outline: write fetchJSON<T> returning Promise<T>, note response.json() is any, and show T lets callers lock in the response shape for compile-time checks.
Create a generic State class with getState and setState
Write class State<T> with private T, constructor(T), getState(): T, and setState(T). Binding a generic class parameter so methods share one consistent type. Using any instead of T, erasing type safety.
Write a generic type-safe getProperty using keyof
Command of TypeScript generics and keyof for compile-time property access. Declare generic T, accept key as keyof T, and return T[K]. Using any or string for the key, which erases type safety and allows invalid properties.
Strategies to type querySelector results as HTMLInputElement
Tests whether you know safe ways to narrow querySelector's Element or null to HTMLInputElement. A strong answer compares type assertions with generic querySelector calls, and insists on null checks. Red flag: asserting without runtime validation.
What is the purpose of the implements keyword?
Tests compile-time contract enforcement in TypeScript. Explain that implements checks class-to-interface compatibility at compile time with no runtime overhead, then code a CacheService with get and set methods.
How would you model fetchItem's return type with generics and conditional types?
Define base and extended Item, return T extends true ? ExtendedItem : BaseItem, and overload the plain boolean case. linking a generic boolean flag to a conditional return type.
Write a generic ApiResponse<T> type with success and error states
Define two interfaces sharing a status literal, one with data: T and the other with error: { code; message; }. modeling exclusive states with discriminated unions and generics.
How do you type a function with two possible response shapes?
This checks TypeScript union types for API responses. Define a union of Product[] and a message object, use a type guard to narrow it at runtime, and return that.
Create a generic getProperty using generics and keyof
Whether you can constrain a generic key with keyof and return the exact property type. Use T for the object and K extends keyof T for the key, returning T[K]. Using string for the key allows invalid properties and erases the return type.
Explain the difference between any and unknown, and demonstrate type-safe narrowing
This tests your grasp of TypeScript top types: any disables checking while unknown forces narrowing. A strong answer defines both, accepts unknown, and uses typeof or a type guard before operating. Red flag: saying they are equivalent or relying on as casts.
What is noImplicitAny and why is it best practice?
State that noImplicitAny errors when inference fails, forcing explicit types instead of plain any. Your grasp of TypeScript's silent any fallback and safety loss. Calling it stylistic or ignoring runtime risks.
What are Swift generics, why useful, and write a swap function?
This tests parametric polymorphism and type-safe reuse. A strong answer defines generics as placeholder types for reusable code, then writes a swap<T> function using inout parameters. Red flag: confusing generics with Any or omitting inout.
What is an optional in Swift? Demonstrate two safe unwrapping methods.
This checks Swift type safety and nil-handling. A strong answer defines Optional as an enum, demonstrates if let binding, and shows the nil-coalescing operator ?? for defaults. Avoid suggesting force-unwrapping with ! as a safe pattern.
Swift Enums: Type-Safe Choice Modeling
A Swift enum is a closed menu of possibilities the compiler tracks exhaustively. Use it to replace string constants or model a network result state. Adding a case without updating every switch breaks compile-time safety if you rely on a default clause.
How do you model Product and safely parse JSON into List<Product>?
Tests bridging dynamic JSON to Dart's type system. A strong answer uses an immutable Product with a factory constructor that validates fields and converts types, mapping over the list. Red flag: leaving everything dynamic or assuming perfect API data.
Typing `fetch` Responses in TypeScript
The `fetch` promise resolves to a generic `Response`, not your typed data. You must first parse the body with `.json()`, then assert the type of the resulting data. This is essential for all API calls.
Type-Safe DOM Selection in TypeScript
TypeScript knows DOM types but can't guarantee an element exists. Selecting an element returns `Type | null`, forcing you to handle the `null` case. This prevents runtime errors when your script runs before the DOM element loads.
Get Type Safety bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.