Top Interview Questions
TypeScript is an open-source programming language developed and maintained by Microsoft. It is a superset of JavaScript, meaning all valid JavaScript code is also valid TypeScript code. However, TypeScript introduces additional features, primarily static typing, which helps developers catch errors early during the development process, rather than at runtime. Since its introduction in 2012, TypeScript has gained widespread popularity, especially in large-scale application development, due to its ability to make code more maintainable, readable, and scalable.
TypeScript compiles down to plain JavaScript, which means it can run on any environment that supports JavaScript, including browsers, Node.js, and other JavaScript engines. This makes TypeScript highly compatible while providing the developer with advanced features that are not available in vanilla JavaScript.
Static Typing:
One of TypeScript’s core features is static typing. This allows developers to define the type of variables, function parameters, and return values. For instance, a variable can be explicitly declared as a string, number, or boolean. Static typing enables the compiler to detect errors at compile-time, which reduces runtime errors and makes debugging easier.
let name: string = "Yash";
let age: number = 25;
Type Inference:
Even if a developer does not explicitly declare a type, TypeScript can infer it based on the assigned value. This ensures a balance between type safety and developer convenience.
let score = 100; // TypeScript infers score as number
Interfaces:
Interfaces in TypeScript define the structure of objects, providing contracts that objects must adhere to. They help enforce consistency across the codebase and make it easier to work in teams.
interface Person {
name: string;
age: number;
}
let employee: Person = { name: "Yash", age: 25 };
Classes and Object-Oriented Programming:
TypeScript enhances JavaScript’s class syntax by adding features like access modifiers (public, private, protected) and abstract classes, allowing developers to write more structured and object-oriented code.
class Employee {
private id: number;
public name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
getDetails(): string {
return `${this.name} (${this.id})`;
}
}
let emp = new Employee(101, "Yash");
console.log(emp.getDetails());
Enums:
Enums are a way to define a set of named constants, making code more readable and maintainable.
enum Direction {
Up,
Down,
Left,
Right
}
let move: Direction = Direction.Up;
Generics:
Generics allow the creation of reusable components that can work with multiple types instead of a single one. This is particularly useful for data structures and functions that should handle a variety of types safely.
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("Hello TypeScript");
Modules and Namespaces:
TypeScript supports modular programming by allowing developers to split code into multiple files and use imports and exports. This promotes code reusability and maintainability in large projects.
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
// main.ts
import { add } from './math';
console.log(add(5, 10));
Type Aliases and Union Types:
TypeScript allows developers to create custom types using type aliases and also supports union types to handle multiple possible types for a variable.
type ID = string | number;
let userId: ID = 101; // can also be a string
Early Error Detection:
TypeScript’s static typing helps catch errors during compilation rather than at runtime. This is especially beneficial in large applications where debugging runtime errors can be complex and time-consuming.
Improved Code Quality:
With TypeScript, developers can write cleaner, more predictable code using features like interfaces, classes, and strict typing. This leads to better maintainability and fewer bugs.
Enhanced Developer Productivity:
TypeScript integrates seamlessly with popular code editors like Visual Studio Code, providing intelligent code completion, type checking, and refactoring tools. These features significantly enhance developer productivity.
Scalability:
TypeScript is particularly suited for large-scale projects. Its type system and modular structure make it easier to manage complex codebases.
Compatibility with JavaScript:
Since TypeScript is a superset of JavaScript, existing JavaScript code can be gradually migrated to TypeScript. This makes adoption smooth for projects with an existing JavaScript codebase.
Strong Community and Ecosystem:
TypeScript has a strong community and is widely adopted in the industry. Many modern frameworks, such as Angular, NestJS, and Deno, are built with TypeScript in mind.
While JavaScript is a dynamic, interpreted language, TypeScript adds a static type system and compiles down to JavaScript. Here’s a comparison:
| Feature | JavaScript | TypeScript |
|---|---|---|
| Typing | Dynamic | Static |
| Error Checking | Runtime | Compile-time |
| Object-Oriented Features | Limited | Full support (classes, interfaces, access modifiers) |
| Tooling Support | Basic | Excellent (VS Code, IntelliSense) |
| Code Scalability | Moderate | High |
| Adoption | Universal | Growing rapidly |
Angular:
Angular, a popular front-end framework, is built entirely with TypeScript. Using TypeScript in Angular projects enhances type safety and enables better tooling and code completion.
React:
While React is primarily JavaScript-based, using TypeScript with React provides benefits like prop type validation and more predictable component behavior.
type Props = { name: string; age: number };
const Person: React.FC<Props> = ({ name, age }) => (
<div>{name} is {age} years old</div>
);
Node.js:
TypeScript can also be used in backend development with Node.js. Using TypeScript in Node projects provides better type safety and reduces runtime errors in server-side code.
Vue.js:
Vue 3 supports TypeScript natively, allowing developers to write strongly typed components for better maintainability.
TypeScript requires a compiler (tsc) to convert .ts files into JavaScript. The compilation process can be customized using a tsconfig.json file, which specifies compiler options, file inclusion/exclusion, module systems, and more.
Example tsconfig.json:
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true,
"outDir": "./dist",
"esModuleInterop": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
Key compiler options:
target: Specifies the JavaScript version for output (ES5, ES6, etc.).
module: Defines the module system (CommonJS, ESNext, etc.).
strict: Enables all strict type-checking options.
outDir: Directory where compiled JavaScript files are stored.
Answer:
TypeScript is an open-source programming language developed by Microsoft. It is a superset of JavaScript, which means every valid JavaScript code is also valid TypeScript code. TypeScript adds static typing and object-oriented features to JavaScript, making it easier to write large-scale applications.
Key features:
Optional static typing
Type inference
Interfaces and classes
Enums
Generics
Advanced tooling support
| Feature | JavaScript | TypeScript |
|---|---|---|
| Type Checking | Dynamic | Static (optional) |
| Compilation | Not required | Requires compilation to JS |
| Support for OOP | Limited (ES6 classes) | Full support (interfaces, classes, access modifiers) |
| IDE Support | Basic | Advanced (IntelliSense, autocomplete) |
| Error Detection | Runtime | Compile-time |
Answer:
Type Safety: Helps catch errors at compile-time rather than runtime.
Improved IDE Support: Provides IntelliSense, auto-completion, and better refactoring support.
Scalability: Suitable for large projects because of classes, interfaces, and modules.
Code Maintainability: Easier to understand and maintain code.
Cross-Platform: Compiles to plain JavaScript, compatible with all browsers.
Answer:
A type defines the shape and behavior of data. TypeScript provides built-in types such as:
number
string
boolean
any
void
null / undefined
never
Example:
let age: number = 25;
let name: string = "Yash";
let isActive: boolean = true;
let data: any = "Can be anything";
any type?Answer:
The any type allows a variable to hold any type of value. It disables type checking for that variable.
Example:
let value: any = 10;
value = "Hello"; // No error
value = true; // Still no error
Note: Using any often defeats the purpose of TypeScript, so it should be used sparingly.
Answer:
Interfaces define a contract for objects, specifying which properties or methods an object should have. They help in type-checking object structures.
Example:
interface Person {
name: string;
age: number;
greet(): void;
}
let user: Person = {
name: "Yash",
age: 25,
greet() {
console.log("Hello!");
}
};
Answer:
TypeScript supports object-oriented programming. Classes can have properties, methods, constructors, and access modifiers (public, private, protected).
Example:
class Employee {
private id: number;
public name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
display(): void {
console.log(`Employee ID: ${this.id}, Name: ${this.name}`);
}
}
let emp = new Employee(1, "Yash");
emp.display();
Answer:
Enums allow you to define a set of named constants.
Example:
enum Direction {
Up = 1,
Down,
Left,
Right
}
let move: Direction = Direction.Left;
console.log(move); // Output: 3
Answer:
A tuple is an array with fixed types at each position.
Example:
let person: [string, number];
person = ["Yash", 25]; // Valid
// person = [25, "Yash"]; // Error
let, const, and var in TypeScript| Keyword | Scope | Reassignable | Hoisting |
|---|---|---|---|
var |
Function | Yes | Yes |
let |
Block | Yes | No |
const |
Block | No | No |
Answer:
Union types allow a variable to hold multiple types.
Example:
let value: string | number;
value = "Hello"; // Valid
value = 25; // Valid
// value = true; // Error
Answer:
Type assertion tells the compiler to treat a variable as a specific type.
Syntax:
let someValue: any = "Hello World";
let strLength: number = (someValue as string).length;
Answer:
Generics allow you to create reusable components that work with multiple types.
Example:
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("Hello");
let output2 = identity<number>(100);
interface and type| Feature | Interface | Type Alias |
|---|---|---|
| Extension | Can extend other interfaces | Can use intersections (&) |
| Declaration Merge | Yes | No |
| Use Case | Objects, class contracts | Union, tuple, primitive types |
Answer:
TypeScript code is compiled into JavaScript using the TypeScript compiler (tsc).
Steps:
Install TypeScript: npm install -g typescript
Compile: tsc filename.ts → produces filename.js
Run JS in browser or Node.js
undefined and nullundefined → variable declared but not assigned.
null → variable explicitly assigned "no value".
Example:
let a: number;
console.log(a); // undefined
let b: number | null = null;
console.log(b); // null
never type?Answer:
never represents a value that never occurs. It is used in functions that throw errors or run infinitely.
Example:
function error(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while(true) {}
}
Detects errors before runtime
Supports OOP concepts
Provides modular architecture with ES modules
Works well with modern frameworks like Angular, React, Node.js
Easier refactoring and code maintenance
Answer:
Decorators are annotations used to modify classes or methods. They are mostly used in Angular.
Example:
function log(target: any, key: string) {
console.log(`${key} method called`);
}
class Calculator {
@log
add(a: number, b: number) {
return a + b;
}
}
unknown type in TypeScript?Answer:
The unknown type is similar to any, but it is safer because you cannot perform operations on it directly without type checking.
Example:
let value: unknown;
value = 10;
value = "Hello";
let str: string;
// str = value; // Error
if (typeof value === "string") {
str = value; // OK after type check
}
any and unknown?| Feature | any | unknown |
|---|---|---|
| Assignment | Can assign to any type | Can’t assign without type check |
| Safety | Unsafe | Safe |
| Use Case | Legacy code, dynamic data | Safer alternative to any |
Answer:
Modules are files that export code (variables, functions, classes) so it can be imported in other files. They help organize code in large projects.
Example:
math.ts
export function add(a: number, b: number): number {
return a + b;
}
app.ts
import { add } from "./math";
console.log(add(5, 10));
Answer:
Namespaces group related code inside a single logical unit. They are mostly used in legacy TypeScript code for modularization.
Example:
namespace Utility {
export function log(message: string) {
console.log(message);
}
}
Utility.log("Hello World!");
| Feature | Module | Namespace |
|---|---|---|
| Syntax | export / import |
namespace keyword |
| Scope | File-based | Can be multiple in one file |
| Use Case | Modern code, ES6 style | Older TypeScript projects |
| Loading | Supports lazy loading | Always loaded |
Answer:
Access modifiers control visibility of class members:
public → accessible everywhere (default)
private → accessible only inside the class
protected → accessible in the class and its subclasses
Example:
class Person {
public name: string;
private age: number;
protected gender: string;
constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
}
Answer:
A constructor is a special method used to initialize class properties.
Example:
class Employee {
constructor(public id: number, public name: string) {}
}
let emp = new Employee(1, "Yash");
console.log(emp.name); // Output: Yash
Answer:
TypeScript supports method overloading by allowing multiple type signatures for the same method.
Example:
class Calculator {
add(a: number, b: number): number;
add(a: string, b: string): string;
add(a: any, b: any): any {
return a + b;
}
}
let calc = new Calculator();
console.log(calc.add(5, 10)); // 15
console.log(calc.add("Hello ", "TS")); // Hello TS
Answer:
readonly makes class or interface properties immutable after initialization.
Example:
class Book {
readonly title: string;
constructor(title: string) {
this.title = title;
}
}
let book = new Book("TypeScript Guide");
// book.title = "New Title"; // Error
Answer:
Optional properties are declared using ? and may or may not be present in an object.
Example:
interface User {
name: string;
age?: number;
}
let user1: User = { name: "Yash" };
let user2: User = { name: "Amit", age: 25 };
interface and abstract class?| Feature | Interface | Abstract Class |
|---|---|---|
| Implementation | Only declarations | Can have implementations |
| Instantiation | Cannot instantiate | Cannot instantiate |
| Multiple Inheritance | Supports multiple interfaces | Single inheritance only |
| Use Case | Contract for objects | Base class with shared logic |
ReadonlyArray in TypeScript?Answer:
ReadonlyArray<T> prevents modification of the array elements.
Example:
let numbers: ReadonlyArray<number> = [1, 2, 3];
// numbers.push(4); // Error
// numbers[0] = 0; // Error
Answer:
TypeScript allows optional elements and rest elements in tuples.
Example:
let tuple1: [string, number?] = ["Yash"];
let tuple2: [number, ...string[]] = [1, "a", "b"];
Answer:
Literal types allow variables to hold only specific values.
Example:
let direction: "Up" | "Down" | "Left" | "Right";
direction = "Up"; // OK
// direction = "Forward"; // Error
interface and type for objects?Both can define object shapes
interface supports declaration merging
type can define unions, intersections, primitives
In modern TypeScript, interfaces are preferred for object contracts
Answer:
Conditional types allow types to depend on other types.
Example:
type Check<T> = T extends string ? "Yes" : "No";
type A = Check<string>; // Yes
type B = Check<number>; // No
Answer:
Mapped types allow you to create new types by transforming properties of an existing type.
Example:
type Person = { name: string; age: number };
type ReadonlyPerson = { readonly [K in keyof Person]: Person[K] };
keyof operator in TypeScript?Answer:
keyof returns the keys of a type as a union.
Example:
type Person = { name: string; age: number };
type PersonKeys = keyof Person; // "name" | "age"
typeof type operator in TypeScript?Answer:
typeof can be used to get the type of a variable or property.
Example:
let name = "Yash";
type NameType = typeof name; // string
Answer:
Optional: Use ?
Nullable: Use | null
Example:
interface User {
name: string;
age?: number | null;
}
Answer:
Utility types are built-in generic types to transform or manipulate types. Examples:
Partial<T> → makes all properties optional
Required<T> → makes all properties required
Readonly<T> → makes all properties readonly
Pick<T, K> → picks some properties from T
Omit<T, K> → omits some properties from T
Example:
interface User {
name: string;
age: number;
}
type PartialUser = Partial<User>; // { name?: string; age?: number }
Answer:
TypeScript provides advanced types to model complex scenarios:
Union Types – variable can hold multiple types (string | number).
Intersection Types – combine multiple types (type A = B & C).
Literal Types – restrict a value to specific constants ("Up" | "Down").
Mapped Types – transform types dynamically ({ [K in keyof T]: ... }).
Conditional Types – type depends on another type (T extends U ? X : Y).
Utility Types – built-in transformations (Partial<T>, Pick<T>).
Index Types – access keys dynamically (keyof T, T[K]).
Example:
type Person = { name: string; age: number };
type ReadonlyPerson = { readonly [K in keyof Person]: Person[K] };
Answer:
Module-based architecture – split code into multiple files using import/export.
Namespaces – rarely used now; modules are preferred.
tsconfig.json – configure compiler options (strict, esModuleInterop, target).
Linting – ESLint with TypeScript plugin for consistent code.
Type safety – strict typing to prevent runtime errors.
Interface & Type usage – define contracts for classes and objects.
Generics – reusable and flexible components.
Build tools – Webpack, Rollup, or Vite for bundling.
Answer:
Generics allow creating reusable components with type flexibility.
Example:
function identity<T>(arg: T): T {
return arg;
}
interface Response<T> {
data: T;
error: string | null;
}
const res: Response<number> = { data: 100, error: null };
Use cases:
API responses (Response<T>).
Utility functions (e.g., arrays, filters).
Reusable classes (e.g., Stack<T>).
Answer:
TypeScript automatically infers types based on assigned values.
Explicit types are needed when:
The variable is declared without initialization.
You want stricter contracts or public APIs.
You deal with any values from dynamic sources.
Example:
let name = "Yash"; // inferred as string
let id: number; // explicit type
Answer:
Angular uses TypeScript decorators to manage dependency injection.
Example:
@Injectable({ providedIn: 'root' })
export class ApiService {
constructor(private http: HttpClient) {}
}
@Component({...})
export class AppComponent {
constructor(private api: ApiService) {}
}
TypeScript’s types and interfaces make DI type-safe.
Helps in testing, modular design, and reusability.
Answer:
Declaration merging happens when two declarations with the same name combine into one.
Example:
interface User {
name: string;
}
interface User {
age: number;
}
const u: User = { name: "Yash", age: 25 }; // merged interface
Use case:
Extending libraries.
Adding custom properties to third-party types.
any, unknown, and strict type safety in large apps?Answer:
Avoid any unless necessary; prefer unknown + type narrowing.
Use type guards and assertions.
Enable strict in tsconfig.json for strict checks.
Example:
function process(value: unknown) {
if (typeof value === 'string') {
console.log(value.toUpperCase());
}
}
interface and type in advanced scenarios?| Feature | Interface | Type Alias |
|---|---|---|
| Extending | interface A extends B |
type A = B & C |
| Declaration Merging | Supported | Not supported |
| Use Case | Objects, Classes | Objects, Primitives, Unions |
| Recommended | Public APIs, Contracts | Complex types or unions |
Answer:
Mixins allow reusing code across classes.
Example:
class CanEat {
eat() { console.log("Eating"); }
}
class CanWalk {
walk() { console.log("Walking"); }
}
class Person {}
interface Person extends CanEat, CanWalk {}
applyMixins(Person, [CanEat, CanWalk]);
function applyMixins(derived: any, bases: any[]) {
bases.forEach(base => {
Object.getOwnPropertyNames(base.prototype).forEach(name => {
derived.prototype[name] = base.prototype[name];
});
});
}
const p = new Person();
p.eat();
p.walk();
Answer:
Type guards narrow down a type to a specific type.
Built-in:
if (typeof value === 'string') { ... }
Custom Type Guard:
interface Fish { swim(): void; }
interface Bird { fly(): void; }
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
let pet: Fish | Bird = ...;
if (isFish(pet)) pet.swim();
Answer:
TypeScript supports Promises, async/await, and typed responses:
async function fetchData(): Promise<string> {
const response = await fetch("https://api.example.com/data");
const data: string = await response.text();
return data;
}
Use generic interfaces for typed API responses.
Helps avoid runtime type errors.
Answer:
Use tsconfig.json with settings:
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true
}
}
Compile using tsc or use ts-node for execution.
Use type definitions (@types/node) for Node.js APIs.
Use ES6 modules (import/export) instead of CommonJS for better tree-shaking.
Avoid default exports for named exports to optimize bundling.
Example:
export function add(a: number, b: number) { return a + b; }
export function multiply(a: number, b: number) { return a * b; }
Answer:
Decorators modify classes, methods, or properties at runtime.
Often used in Angular, NestJS, and logging/tracing libraries.
Example (Method decorator):
function Log(target: any, key: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling ${key} with args`, args);
return original.apply(this, args);
};
}
class Calculator {
@Log
add(a: number, b: number) { return a + b; }
}
new Calculator().add(2, 3);
Answer:
Index signatures define types for dynamic object properties.
interface StringMap {
[key: string]: string;
}
let dict: StringMap = { name: "Yash", city: "Delhi" };
Answer:
function merge<T extends object, U extends object>(obj1: T, obj2: U): T & U {
return { ...obj1, ...obj2 };
}
const merged = merge({ name: "Yash" }, { age: 25 });
Constraints (extends object) ensure safe operations.
React: .tsx files, React.FC or React.FunctionComponent, props and state typing.
Angular: services, components, directives, strong DI with typed interfaces.
Always strictly type props, state, services, and observables.
Use source maps ("sourceMap": true) to debug TS in browser or Node.
Combine VSCode breakpoints with type hints.
Enable strict compiler options to catch errors early.
Use ts-node or nodemon for live debugging in Node.js.
Use interfaces for state and typed actions.
Example (Redux):
interface AppState { count: number; }
const increment = (payload: number) => ({ type: 'INCREMENT', payload } as const);
Avoid any to leverage TypeScript’s type safety.
Enable strict and noImplicitAny in tsconfig.json.
Use interfaces over type aliases for object contracts.
Leverage Generics for reusable code.
Avoid any; prefer unknown + type guards.
Use decorators for cross-cutting concerns.
Modularize with ES6 modules, avoid global namespace pollution.
Enable linting and formatting (ESLint, Prettier).
Keep tsconfig.json optimized for production (strict null checks, noUnusedLocals).
unknown type in TypeScript?Answer:
The unknown type is similar to any but safer. You cannot perform operations on a variable of type unknown without first checking its type.
Example:
let value: unknown;
value = 10;
value = "Hello";
let str: string;
// str = value; // Error
if (typeof value === "string") {
str = value; // Works after type check
}
any and unknown| Feature | any |
unknown |
|---|---|---|
| Assignment | Can assign to any type | Requires type check |
| Safety | Unsafe | Safe |
| Use Case | Legacy code, dynamic data | Safer alternative to any |
Answer:
Modules allow you to split code into multiple files. Each module can export variables, functions, or classes and import them in other files.
Example:
math.ts
export function add(a: number, b: number): number {
return a + b;
}
app.ts
import { add } from "./math";
console.log(add(5, 10));
Answer:
Namespaces group related code together. Unlike modules, they can exist in a single file or across multiple files.
Example:
namespace Utility {
export function log(message: string) {
console.log(message);
}
}
Utility.log("Hello World!");
| Feature | Module | Namespace |
|---|---|---|
| Syntax | export / import |
namespace keyword |
| Scope | File-based | Can span multiple files |
| Use Case | Modern ES6 projects | Legacy TypeScript projects |
| Loading | Supports lazy loading | Always loaded |
Answer:
public → accessible everywhere (default).
private → accessible only within the class.
protected → accessible within the class and subclasses.
Example:
class Person {
public name: string;
private age: number;
protected gender: string;
constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
}
Answer:
A constructor is a special method used to initialize class properties.
Example:
class Employee {
constructor(public id: number, public name: string) {}
}
let emp = new Employee(1, "Yash");
console.log(emp.name); // Yash
Answer:
TypeScript allows multiple type signatures for a method.
Example:
class Calculator {
add(a: number, b: number): number;
add(a: string, b: string): string;
add(a: any, b: any): any {
return a + b;
}
}
let calc = new Calculator();
console.log(calc.add(5, 10)); // 15
console.log(calc.add("Hello ", "TS")); // Hello TS
Answer:
readonly properties cannot be modified after initialization.
Example:
class Book {
readonly title: string;
constructor(title: string) {
this.title = title;
}
}
let book = new Book("TypeScript Guide");
// book.title = "New Title"; // Error
Answer:
Optional properties are declared with ? and may or may not be present.
Example:
interface User {
name: string;
age?: number;
}
let user1: User = { name: "Yash" };
let user2: User = { name: "Amit", age: 25 };
interface and abstract class| Feature | Interface | Abstract Class |
|---|---|---|
| Implementation | Only declarations | Can have implementations |
| Instantiation | Cannot instantiate | Cannot instantiate |
| Multiple Inheritance | Supports multiple interfaces | Single inheritance only |
| Use Case | Contract for objects | Base class with shared logic |
Answer:
ReadonlyArray<T> prevents modification of array elements.
let numbers: ReadonlyArray<number> = [1, 2, 3];
// numbers.push(4); // Error
Answer:
let tuple1: [string, number?] = ["Yash"];
let tuple2: [number, ...string[]] = [1, "a", "b"];
Answer:
Restrict a variable to specific values.
let direction: "Up" | "Down" | "Left" | "Right";
direction = "Up"; // OK
// direction = "Forward"; // Error
Answer:
type Check<T> = T extends string ? "Yes" : "No";
type A = Check<string>; // Yes
type B = Check<number>; // No
Answer:
type Person = { name: string; age: number };
type ReadonlyPerson = { readonly [K in keyof Person]: Person[K] };
keyof operatorAnswer:
Returns the keys of a type as a union.
type Person = { name: string; age: number };
type PersonKeys = keyof Person; // "name" | "age"
typeof type operatorAnswer:
let name = "Yash";
type NameType = typeof name; // string
Answer:
interface User {
name: string;
age?: number | null;
}
Partial<T> → all properties optional
Required<T> → all properties required
Readonly<T> → all properties readonly
Pick<T,K> → picks selected properties
Omit<T,K> → omits selected properties
Example:
interface User { name: string; age: number }
type PartialUser = Partial<User>; // { name?: string; age?: number }
Answer:
Tell the compiler a variable is of a specific type.
let someValue: any = "Hello World";
let strLength: number = (someValue as string).length;