TypeScript Tricky Questions and Answers
Last updated:
Crucial Topics
What is TypeScript?
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds optional static types, classes, and interfaces to JavaScript.
Why do we need TypeScript? What are the differences between TypeScript and JavaScript?
TypeScript provides static typing, which helps catch errors at compile time rather than runtime. It also supports modern JavaScript features and provides better tooling with IntelliSense and code navigation.
Pros and cons of using TS.
Pros:
- Static typing
- Enhanced IDE support
- Early error detection
- Improved code readability and maintainability
Cons:
- Additional compilation step
- Learning curve for developers new to static typing
- Potentially longer development time due to type annotations
How to transform TS code into JS?
Use the TypeScript compiler (tsc
) to compile TypeScript code into JavaScript. The tsconfig.json
file can be used to configure the compilation options.
What is void, and when to use the void type?
The void
type represents the absence of a value. It is commonly used as the return type of functions that do not return a value.
Explain how enums work in TypeScript?
Enums allow you to define a set of named constants. They can be numeric or string-based.
What is an interface?
An interface defines the shape of an object, specifying the types of its properties. It is used for type-checking and ensuring that objects conform to a specific structure.
Explain the various ways to control member visibility in TypeScript.
TypeScript provides three access modifiers: public
, private
, and protected
. public
members are accessible from anywhere, private
members are accessible only within the class, and protected
members are accessible within the class and its subclasses.
What are Generics in TypeScript?
Generics allow you to create reusable components that work with any data type. They provide a way to create functions, classes, and interfaces that can operate on different types while maintaining type safety.
What is the difference between extends and implements in TypeScript?
extends
is used to create a subclass that inherits properties and methods from a parent class. implements
is used to ensure that a class adheres to a specific interface by implementing its properties and methods.
List some of the utility types provided by TypeScript and explain their usage.
Partial<T>
: Makes all properties ofT
optional.Required<T>
: Makes all properties ofT
required.Readonly<T>
: Makes all properties ofT
read-only.Pick<T, K>
: Creates a type by picking a set of propertiesK
fromT
.Omit<T, K>
: Creates a type by omitting a set of propertiesK
fromT
.
What are type assertions in TypeScript?
Type assertions allow you to override the inferred type of a value. They are used when you know more about the type of a value than TypeScript does.
When should you use the unknown type?
The unknown
type is used when you do not know the type of a value. It is safer than any
because it requires type checking before performing operations on the value.
What is the difference between types String in JavaScript and string in TypeScript?
String
in JavaScript is a constructor function for creating string objects, while string
in TypeScript is a primitive type representing string values.
What are string literal types?
String literal types allow you to specify a set of possible string values for a variable. They are useful for creating more precise types.
What are abstract classes? When should you use one?
Abstract classes are classes that cannot be instantiated directly. They are used as base classes for other classes and can contain abstract methods that must be implemented by subclasses.
Explain the tuple types in TypeScript.
Tuples are fixed-length arrays with specific types for each element. They allow you to represent a collection of values with different types.
Explain how tuple destructuring works in TypeScript.
Tuple destructuring allows you to extract values from a tuple and assign them to variables. It provides a concise way to work with tuple elements.
Frequently Asked Questions
Mention some of the features of TypeScript.
- Static typing
- Classes and interfaces
- Modules and namespaces
- Generics
- Type inference
- Decorators
- Union and intersection types
Explain the Components of Typescript.
- TypeScript Compiler (
tsc
): Transforms TypeScript code into JavaScript. - TypeScript Language Service: Provides features like IntelliSense, code navigation, and refactoring.
- TypeScript Language: The syntax and semantics of TypeScript.
Explain the purpose of the never type in TypeScript.
The never
type represents values that never occur. It is used for functions that never return, such as functions that throw exceptions or have infinite loops.
What are union types in TypeScript?
Union types allow a variable to hold values of multiple types. They are defined using the |
operator.
How to make object properties immutable in TypeScript?
Use the Readonly<T>
utility type to make all properties of an object read-only.
How to easily make all properties of an interface optional?
Use the Partial<T>
utility type to make all properties of an interface optional.
What is the difference between keyof and typeof operators? Explain each of them.
keyof
: Takes an object type and produces a string or numeric literal union of its keys.typeof
: Returns the type of a value or variable.
What is the difference between type and interface in TypeScript?
type
: Used to define type aliases, unions, intersections, and mapped types.interface
: Used to define the shape of an object and can be extended or implemented by classes.
What is tsconfig.json file?
tsconfig.json
is a configuration file for the TypeScript compiler. It specifies the root files and compiler options required to compile a TypeScript project.
What is the fundamental difference between Optional Chaining (?.) and Non-null assertion operator (!) in TypeScript?
- Optional Chaining (
?.
): Safely accesses nested properties, returningundefined
if any part of the chain isnull
orundefined
. - Non-null assertion operator (
!
): Asserts that a value is notnull
orundefined
.
What is the difference between void and never types?
void
: Represents the absence of a value, typically used as a return type for functions that do not return a value.never
: Represents values that never occur, used for functions that never return.
What are conditional types? How do you create them?
Conditional types allow you to create types based on a condition. They use the syntax T extends U ? X : Y
.
Does TypeScript support function overloading?
Yes, TypeScript supports function overloading. You can define multiple signatures for a function, and TypeScript will resolve the correct signature based on the arguments passed.
Explain Decorators in TypeScript.
Decorators are special functions that can be applied to classes, methods, properties, and parameters to modify their behavior. They are used for metadata annotations and aspect-oriented programming.
How to use Indexed Access Types?
Indexed access types allow you to access the type of a property of an object type. They use the syntax T[K]
, where T
is the object type and K
is the key.
Can Type aliases be recursive?
Yes, type aliases can be recursive. You can define a type alias that references itself.
Type Aliases vs. Interfaces
While interfaces are ideal for defining object shapes and class contracts, Type Aliases provide a broader range of capabilities, including the ability to define unions, primitives, and tuples. Understanding when to use each can significantly enhance your TypeScript code’s readability and maintainability.
When to Use Interfaces:
- When you need to define a contract for an object or a class.
- For object-oriented programming patterns, where you might extend or implement interfaces.
When to Use Type Aliases:
- When you need to define union or intersection types.
- For simpler object shapes or when you require tuple types.
Interfaces are extendable and can be merged, allowing for a more flexible and scalable way to organize type contracts, especially in large codebases.
Type Aliases, while not extendable, offer composability through unions and intersections, providing a powerful tool for complex type definitions.
What is Namespace and how to declare it?
Namespaces are used to organize code into logical groups and prevent name collisions. They are declared using the namespace
keyword.
What is TypeScript Declare Keyword?
The declare
keyword is used to declare variables, functions, classes, and interfaces that exist in the global scope or are provided by external libraries. It is used to provide type information without defining the actual implementation.
What is ‘satisfies’ in TypeScript and compared to ‘as’?
“satisfies” that validates your value against a type without changing the type inference, ensuring your implementation meets a contract while preserving specific type information.
“as” is a type assertion that forces TypeScript to treat a value as a specific type, potentially bypassing type checking.
Key difference: “satisfies” verifies compatibility while preserving the original inferred type’s precision, whereas “as” overwrites the type inference and can lead to unsafe code if used incorrectly.
Others
Given a type T
, how would you construct a new type that excludes certain properties, similar to the built-in Omit
?
In TypeScript, within a mapped type, the as
keyword is used to rename or filter keys during the transformation. Specifically, it allows you to remap each key in the original type to a new key or to exclude certain keys based on a condition.
In your example:
type MyOmit<T, K extends keyof T> = { [Key in keyof T as Key extends K ? never : Key]: T[Key]}
Key in keyof T
: iterates over all keys ofT
.as Key extends K ? never : Key
: filters out keys that extend (i.e., are assignable to)K
.- If
Key
extendsK
, it maps tonever
, effectively excluding that key from the resulting object because keys mapped tonever
are omitted. - Otherwise, it keeps the key as is.
- If
In essence:
- The
as
allows conditional remapping of keys. - When the condition
Key extends K
is true, the key is mapped tonever
, removing it from the resulting type. - When false, the key remains unchanged.
This technique is how MyOmit
re-creates the behavior of the built-in Omit
type—excluding specific keys from a type.
Summary:
The
as
in the mapped type is used to rename or filter keys conditionally during type transformation.
What is the purpose of the as
keyword in mapped types?
The as
keyword in mapped types is used to rename or filter keys during the transformation of a type. It allows you to create new types based on existing ones by applying conditions to the keys, enabling you to exclude or modify them as needed.
This is particularly useful for creating utility types like Omit
, Pick
, and others, where you want to derive a new type from an existing one while applying specific transformations to its keys.