20 cards · Public · Shuffle

TypeScript & Object-Oriented Design Patterns - Generics, Decorators & SOLID

Master advanced TypeScript features like generics, conditional types, and decorators, alongside essential Object-Oriented Design Patterns and SOLID principles for building robust, scalable software.

Cards in this deck

(20 cards)

Preview terms and definitions before starting your study session.

#1
Term
What are TypeScript Generics and why use them?
Definition
Generics provide a way to create reusable components that can work with a variety of types rather than a single one. They allow you to write code that works for "any" type, while still providing type safety, preventing code duplication and making components more flexible.
typescript5 lines
function identity<T>(arg: T): T {
  return arg;
}
let output = identity<string>("myString"); // output is string
let output2 = identity<number>(123);    // output2 is number
#2
Term
How do you add constraints to a generic type parameter?
Definition
You can constrain a generic type parameter T to extend another type, ensuring that T has at least the properties of that type. This allows you to operate on those properties within the generic function or class.
typescript9 lines
interface Lengthwise {
  length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
  console.log(arg.length); // Now we know 'arg' has a .length property
  return arg;
}
loggingIdentity({ length: 10, value: 3 }); // OK
// loggingIdentity(3); // Error: Argument of type 'number' is not assignable to parameter of type 'Lengthwise'.
#3
Term
Explain user-defined type guards with an example.
Definition
User-defined type guards are functions that return a boolean indicating whether their argument is of a certain type. Their return type is a type predicate, typically parameterName is Type. This tells the TypeScript compiler that if the function returns true, the parameter is of that specific type within the scope where the guard was called.
typescript17 lines
interface Bird { fly(): void; layEggs(): void; }
interface Fish { swim(): void; layEggs(): void; }

function isFish(pet: Bird | Fish): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

function getSmallPet(): Fish | Bird {
  return Math.random() < 0.5 ? { fly: () => {}, layEggs: () => {} } : { swim: () => {}, layEggs: () => {} };
}

let pet = getSmallPet();
if (isFish(pet)) {
  pet.swim(); // TypeScript knows 'pet' is Fish here
} else {
  pet.fly();  // TypeScript knows 'pet' is Bird here
}
#4
Term
What are conditional types and provide a basic example?
Definition
Conditional types allow types to be chosen based on a condition, similar to a ternary operator in JavaScript. They take the form T extends U ? X : Y. If type T is assignable to type U, then the type is X; otherwise, it's Y.
typescript15 lines
type IsString<T> = T extends string ? "Yes" : "No";

type A = IsString<string>; // type A = "Yes"
type B = IsString<number>; // type B = "No"

type TypeName<T> =
  T extends string ? "string" :
  T extends number ? "number" :
  T extends boolean ? "boolean" :
  T extends undefined ? "undefined" :
  T extends Function ? "function" :
  "object";

type C = TypeName<() => void>; // type C = "function"
type D = TypeName<null>;       // type D = "object"
#5
Term
How does the infer keyword enhance conditional types?
Definition
The infer keyword allows you to declare a type variable within the extends clause of a conditional type, which can then be used in the "true" branch. It's used to extract a type from another type.
typescript11 lines
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;

function greet(name: string): string {
  return `Hello, ${name}`;
}

type GreetReturnType = ReturnType<typeof greet>; // type GreetReturnType = string

type ArrayElementType<T> = T extends (infer U)[] ? U : T;
type NumArrayElement = ArrayElementType<number[]>; // type NumArrayElement = number
type StringElement = ArrayElementType<string>;     // type StringElement = string
#6
Term
Explain mapped types and provide a simple example.
Definition
Mapped types allow you to create new types by transforming the properties of an existing type. They iterate over the properties of a type, applying a transformation to each property's name or value. The syntax uses a [P in K] clause, where P is a new property name and K is a union of property keys.
typescript13 lines
type Point = { x: number; y: number; };

// Makes all properties of Point optional
type PartialPoint = {
  [P in keyof Point]?: Point[P];
};
// type PartialPoint = { x?: number; y?: number; }

// Makes all properties of Point readonly
type ReadonlyPoint = {
  readonly [P in keyof Point]: Point[P];
};
// type ReadonlyPoint = { readonly x: number; readonly y: number; }
#7
Term
What does Partial<T> do?
Definition
Partial<T> is a built-in utility type that constructs a type with all properties of T set to optional. This is useful when you want to create an object that might only have a subset of the properties of an existing type.
typescript22 lines
interface Todo {
  title: string;
  description: string;
  completed: boolean;
}

type PartialTodo = Partial<Todo>;
/*
type PartialTodo = {
  title?: string;
  description?: string;
  completed?: boolean;
}
*/

const updateTodo = (todo: Todo, fieldsToUpdate: PartialTodo): Todo => {
  return { ...todo, ...fieldsToUpdate };
};

const myTodo: Todo = { title: "Learn TS", description: "Advanced topics", completed: false };
const updated = updateTodo(myTodo, { completed: true });
// updated is { title: "Learn TS", description: "Advanced topics", completed: true }
#8
Term
What does Pick<T, K> do?
Definition
Pick<T, K> is a built-in utility type that constructs a type by picking a set of properties K (a union of string literals) from type T. It creates a new type containing only the specified properties.
typescript19 lines
interface User {
  id: number;
  name: string;
  email: string;
  age: number;
}

type UserProfile = Pick<User, "name" | "email">;
/*
type UserProfile = {
  name: string;
  email: string;
}
*/

const user: UserProfile = {
  name: "Alice",
  email: "[email protected]"
};
Showing 8 of 20 cards in this deck.
Study All Now