What is TypeScript, and how does it differ from JavaScript?
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds static types to the language, which can help catch errors during development and improve code quality. Unlike JavaScript, TypeScript requires a compilation step.
What are the benefits of using TypeScript?
Explain the different types of variable declarations in TypeScript (var, let, const)
var declares a variable with function scope, let declares a block-scoped variable, and const declares a block-scoped constant that cannot be reassigned. let and const are recommended over var to avoid scope-related issues.
var can be redeclared, but not forlet and const
What are the basic types in TypeScript?
The basic types include boolean, number, string, array, tuple, enum, any, void, null, undefined, never, object, ‘function’, ‘unknown’
Explain the concept of “type inference” in TypeScript.
Type inference is when TypeScript automatically determines the type of a variable based on its initial value. For example, let x = 3; infers x to be of type number.
What is a “union type” in TypeScript?
A union type allows a variable to be one of several types. It is defined using the | symbol.
What is the difference between interface and type aliases in TypeScript?
Both can be used to describe the shape of an object, but interface is more versatile as it allows for declaration merging and extending other interfaces. type aliases can be used for complex types like unions and intersections but cannot be reopened to add new properties.
How do you use generics in TypeScript?
Generics allow you to create reusable components. For example:
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("myString");
interface IProcessor<T> {
result:T;
process(a: T, b: T) => T;
}What is the unknown type in TypeScript?
The unknown type is a type-safe counterpart of any. It means that a value could be anything, but it must be checked before performing operations on it. For example:
let value: unknown;
value = "hello";
if (typeof value === "string") {
console.log(value.toUpperCase());
}What is diff any and unknown?
Anything is assignable to unknown, but unknown isn’t assignable to anything but itself.
while anything is assignable to any and any can assign to anything.
Type Safety:
- any: No type safety. You can perform any operation on a variable of type any without any checks, which can lead to runtime errors.
- unknown: Type-safe. You must perform type checks or type assertions before using a variable of type unknown, ensuring safer code.
Use Cases:
- any: Use when you want to disable type checking. Typically used during gradual migration to TypeScript or when dealing with legacy code.
- unknown: Use when you want to represent a variable of unknown type while maintaining type safety.
Explain the difference between interface and abstract class.
An interface is a purely structural contract that does not provide any implementation, while an abstract class can provide both abstract methods (without implementation) and concrete methods (with implementation). Abstract classes can have state (fields), whereas interfaces cannot.
interface: Supports multiple inheritance. A class can implement multiple interfaces.
abstract class: Supports single inheritance. A class can only extend one abstract (or any other) class but can implement multiple interfaces.
What is the purpose of type assertion in TypeScript?
Type assertions allow you to override the inferred type of a variable when you know more about the variable’s type than TypeScript does. For example:
let someValue: unknown = "this is a string"; let strLength: number = (someValue as string).length;
Explain the never type in TypeScript.
The never type represents values that never occur. It is typically used for functions that always throw an error or never return. For example:
function error(message: string): never {
throw new Error(message);
}
What are decorators in TypeScript?
Decorators are special types of declarations that can be attached to classes, methods, accessors, properties, or parameters. They provide a way to add annotations and a meta-programming syntax. For example:
function log(target: any, key: string) {
console.log(`${key} was called`);
}
class Person {
@log
sayHello() {
console.log("Hello");
}
}
How do you create and use a mapped type in TypeScript?
Mapped types allow you to create new types based on existing ones by transforming their properties. For example:
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
interface User {
name: string;
age: number;
}
const user: Readonly<User> = {
name: "Alice",
age: 30
};Explain conditional types in TypeScript.
Conditional types are a way to express logic that depends on types. For example:
type Message<T> = T extends string ? string : number; let msg: Message<string>; // string let num: Message<number>; // number
What is type narrowing in TypeScript?
Type narrowing is the process of refining a type to a more specific type within a specific scope. It is typically achieved using type guards, such as typeof, instanceof, and custom type guard functions. For example:
function isString(value: any): value is string {
return typeof value === "string";
}
let value: string | number;
if (isString(value)) {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}How do you use the Partial utility type in TypeScript?
The Partial utility type makes all properties of a type optional. For example:
interface User {
name: string;
age: number;
}What is diff enum and const enum ?