TypeScript
/Beginner
Type Inference
Definition
TypeScript's ability to automatically deduce the type of a variable without requiring an explicit type annotation.
Explain Like I'm New
If you write `let x = 10`, TypeScript isn't stupid. It sees the 10 and says, 'Okay, 10 is a number. Therefore, x must forever be a number.' You don't have to explicitly tell it.
Real World Example
Hovering over a variable in VS Code that has no explicit type, and seeing that TS perfectly understood it was a `string[]` based on how you initialized it.
Common Use Cases
- •Keeping code clean and less verbose
- •Relying on return types from standard functions
Terminal Output
bash / terminal
// BAD: Redundant typing
let greeting: string = "Hello World";
// GOOD: Rely on inference
let inferredGreeting = "Hello World";
// TS knows this is a string
// inferredGreeting = 5; // Error!
// FAILS: TS infers 'any' because it has no clues
let unknownData;
unknownData = 5;
unknownData = "Wait, now I'm a string";
Interview Questions
basic
- Do I need to type every single variable in TypeScript?
intermediate
- When does type inference fail and require explicit annotations?
advanced
- How does inference work with Array `.map()`?