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
TypeScript | 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[]
orArray<type>
. - 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 <T>
, allowing it to accept and return values of any type.
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 ofunknown
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:
interface | 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. |
These questions and answers should help prepare for TypeScript interviews by covering fundamental concepts and practical usage.
Top comments (1)
nice one