【Interview Essentials】ommon TypeScript Interview Questions

github: https://github.com/Jessie-jzn
website:https://www.jessieontheroad.com/
1. Why use TypeScript?
1. Static Type Checking
TypeScript’s core advantage is its static type checking, which helps catch common errors during the compile phase rather than runtime. This enhances code reliability and stability.
2. Enhanced Code Editing Experience
TypeScript’s type system enables more accurate code completion, refactoring, navigation, and documentation features in editors, significantly boosting development efficiency.
3. Improved Code Maintainability
Type declarations make understanding code intentions and structure easier, which is particularly beneficial in team development environments.
4. Advanced Language Features
TypeScript supports advanced features not present in JavaScript, such as interfaces, enums, and generics, facilitating the development of more structured and scalable code.
5. Better Tool Support
TypeScript offers various compiler options to optimize generated JavaScript code and supports different JS environments by compiling TypeScript to compatible JavaScript.
2. TypeScript vs. JavaScript
|
JavaScript | |||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Type System | Static typing with compile-time type checks. Types can be specified for variables, function parameters, and return values. | Dynamic typing with runtime type checks, which can lead to type-related runtime errors. | ||||||||||||||||||
| Type Annotations | Supports type annotations to explicitly define types. E.g., let name: string = "Alice"; | No type annotations. Types are determined at runtime. | ||||||||||||||||||
| Compilation | Requires compilation to JavaScript. TypeScript compiler checks for type errors and generates equivalent JavaScript code. | Runs directly in browsers or Node.js without a compilation step. | ||||||||||||||||||
| Object-Oriented Programming | Richer OOP features such as classes, interfaces, abstract classes, and access modifiers. | Basic OOP features with prototype-based inheritance. | ||||||||||||||||||
| Advanced Features | Includes all ES6 and ES7 features, plus additional features like generics, enums, and decorators. | Supports ES6 and later standards, but lacks some of the advanced features provided by TypeScript. |
3. Basic Data Types in TypeScript
- Boolean: Represents true or false values.
- Number: Represents both integer and floating-point numbers.
- String: Represents textual data, using single or double quotes.
-
Array: Represents a collection of values of a specified type, using type[] or Array
. - Tuple: Represents an array with a fixed number of elements with specified types.
- Enum: Represents a set of named constants.
- Any: Represents any type of value. Provides no type checking.
- Void: Represents the absence of a value, commonly used as the return type of functions that do not return a value.
- Null and Undefined: Represent the absence of a value and uninitialized state, respectively.
- Never: Represents values that never occur, such as functions that throw errors or run indefinitely.
- Object: Represents non-primitive types.
4. What are Generics in TypeScript? How are they used?
Generics allow functions, classes, and interfaces to work with any type while still enforcing type safety.
Example:
function identity<T>(arg: T): T {
return arg;
}
const numberIdentity = identity<number>(42);
const stringIdentity = identity<string>("Hello");
In this example, the identity function uses a generic
5. Difference Between unknown and any in TypeScript
- any Type: Represents any type of value and bypasses all type checking. It can be assigned any value without type checks.
- unknown Type: Represents an unknown type. Values of unknown type must be checked before they can be used, providing a safer way to handle values whose type is uncertain.
let anyVar: any;
let unknownVar: unknown;
anyVar = 5;
anyVar.toUpperCase(); // No compile-time error, but might cause runtime error
unknownVar = "Hello";
if (typeof unknownVar === "string") {
unknownVar.toUpperCase(); // Type check ensures safety
}
6. Difference Between readonly Modifier and const Keyword
- readonly Modifier: Used on object properties to make them immutable after initialization.
- const Keyword: Used to declare variables with immutable references. The object's properties can still be modified.
const obj = { name: "John" };
obj.name = "Doe"; // Allowed
interface User {
readonly id: number;
name: string;
}
const user: User = { id: 1, name: "John" };
user.name = "Doe"; // Allowed
user.id = 2; // Error, `id` is readonly
7. Decorators in TypeScript
Decorators are a special TypeScript feature that allows adding metadata or modifying classes, methods, properties, or parameters.
Types:
- Class Decorators: Applied to class constructors to modify class behavior or add metadata.
- Method Decorators: Applied to methods to change their behavior or add metadata.
- Accessor Decorators: Applied to get or set accessors to modify their behavior.
- Property Decorators: Applied to class properties to add metadata or modify their behavior.
- Parameter Decorators: Applied to method parameters to add metadata.
Examples:
- Class Decorator:
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return `Hello, ${this.greeting}`;
}
}
- Method Decorator:
function logMethod(target: any, propertyName: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Method ${propertyName} called with args: ${JSON.stringify(args)}`);
return originalMethod.apply(this, args);
};
}
class Calculator {
@logMethod
add(a: number, b: number): number {
return a + b;
}
}
Usage:
Decorators are enabled by setting experimentalDecorators to true in tsconfig.json.
8. Difference Between interface and type
interface and type are both used to define object types, but they have some differences:
|
type |
||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Basic Usage | Defines the shape of objects, including properties and methods. | Defines primitive types, object types, union types, intersection types, etc. | |||||||||||||||||||||
| Extension | Supports declaration merging. Multiple declarations of the same interface are automatically merged. | Does not support declaration merging. | |||||||||||||||||||||
| Union and Intersection Types | Not supported. | Supports union (` | |||||||||||||||||||||
| Primitive Type Aliases | Not supported. | Supports aliasing primitive types. | |||||||||||||||||||||
| Mapped Types | Not supported. | Supports mapped types. | |||||||||||||||||||||
| Class Implementation | Supports class implementation using implements. | Does not support direct class implementation. |
The above is the detailed content of 【Interview Essentials】ommon TypeScript Interview Questions. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1385
52
What should I do if I encounter garbled code printing for front-end thermal paper receipts?
Apr 04, 2025 pm 02:42 PM
Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...
Who gets paid more Python or JavaScript?
Apr 04, 2025 am 12:09 AM
There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.
How to merge array elements with the same ID into one object using JavaScript?
Apr 04, 2025 pm 05:09 PM
How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...
Demystifying JavaScript: What It Does and Why It Matters
Apr 09, 2025 am 12:07 AM
JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.
The difference in console.log output result: Why are the two calls different?
Apr 04, 2025 pm 05:12 PM
In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
TypeScript for Beginners, Part 2: Basic Data Types
Mar 19, 2025 am 09:10 AM
Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript
How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website?
Apr 04, 2025 pm 05:36 PM
Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...
Can PowerPoint run JavaScript?
Apr 01, 2025 pm 05:17 PM
JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.


