今日已更新 390 条资讯 | 累计 41610 条内容
关于我们

5 common TypeScript interview questions

ReactChallenges 2026年09月10日 17:40 0 次阅读 来源:Dev.to

These five questions show up in almost every TypeScript interview. They're not tricky syntax puzzles. They test whether you understand the type system well enough to use it on purpose instead of just making the compiler happy. any vs unknown any turns type checking off. Once a value is any , TypeScript stops protecting you and mistakes slip through until runtime. unknown is the safe counterpart: it can hold anything, but you must narrow it before using it. const a : any = " hello " ; a . toUpperCase (); // ✅ no error a . thisDoesNotExist (); // ✅ no error either 💀 const u : unknown = " hello " ; u . toUpperCase (); // ❌ 'u' is of type 'unknown' if ( typeof u === " string " ) { u . toUpperCase (); // ✅ narrowed to string } Reach for unknown when the type is genuinely unknown, like API responses, JSON.parse , or catch variables, and never reach for any . interface vs type Both describe object shapes and are mostly interchangeable. The real differences are what each one can express. interface supports declaration merging ; type doesn't. type can express unions, intersections, tuples, and primitives; interface only describes object-like shapes. interface extends with extends ; type composes with & . interface User { name : string ; } interface User { age : number ; } // merged: { name: string; age: number } type Id = string | number ; // only possible with type Declaration merging cuts both ways: it lets libraries augment existing types (like extending Window ), but it can also merge a typo into a valid type. A common convention is interface for object APIs and type for unions and computed types. Generics Generics let you write code that works with many types while preserving the relationship between input and output. Without them you'd duplicate the function per type or fall back to any and lose the return type. function first < T > ( items : T []): T | undefined { return items [ 0 ]; } const n = first ([ 1 , 2 , 3 ]); // number | undefined const s = first ([ " a " , "

本文内容来源于互联网,版权归原作者所有
查看原文