My Typescript Flashcards

1
Q

How do you declare a variable with a specific type in TypeScript?

A

Use the let or const keyword followed by the variable name and a type annotation. For example:

let name: string;
const age: number = 30;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the syntax for defining a function with typed parameters and a return type in TypeScript?

A

Define the function with parameter types and a return type. For example:

function sum(lhs: number, rhs: number): number {
  return lhs + rhs;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you create an array of numbers in TypeScript?

A

Use square brackets with the type number. For example:

const numbers: number[] = [1, 2, 3];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a tuple in TypeScript, and how do you define one?

A

A tuple is an array with a fixed number of elements of specified types. Define it using square brackets with types. For example:

let book: [string, number];
book = ["sample", 1980];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you define a class with private, protected, and public properties in TypeScript?

A

Use the class keyword and specify access modifiers for each property. For example:

class Dimension {
  private length: number;
  protected width: number;
  public height: number;

  constructor(l: number, w: number, h: number) {
    this.length = l;
    this.width = w;
    this.height = h;
  }

  getLength(): number {
    return this.length;
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is an interface in TypeScript, and how do you implement it in a class?

A

An interface defines a contract for object shapes. Implement it in a class using the implements keyword. For example:

interface Area {
  area(): number;
}

class Rectangle implements Area {
  constructor(public length: number, public width: number) {}

  area(): number {
    return this.length * this.width;
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you handle exceptions in TypeScript?

A

Use try…catch blocks to handle exceptions. For example:

try {
  // code that may throw an error
} catch (e) {
  console.error(`An error occurred: ${e}`);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is optional chaining in TypeScript, and how is it used?

A

Optional chaining allows safe access to nested object properties that might be null or undefined. Use the ?. operator. For example:

console.log(result?.pii?.age);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you define a generic function in TypeScript?

A

Use angle brackets to specify a generic type parameter. For example:

function getFirst<T>(arr: T[]): T | undefined {
  return arr.length > 0 ? arr[0] : undefined;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the purpose of utility types like Pick and Omit in TypeScript?

A

Utility types allow you to create new types by selecting or omitting properties from existing types. For example:

interface UserForm {
  email: string;
  password: string;
  phoneNumber?: string;
}

type LoginForm = Pick<UserForm, "email" | "password">;
type ContactForm = Omit<UserForm, "password">;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is type assertion in TypeScript, and how is it used?

A

Type assertion tells the compiler to treat a variable as a specific type. Use as or angle bracket syntax. For example:

let someValue: any = "Hello, world!";
let strLength: number = (someValue as string).length;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are union types in TypeScript?

A

Union types allow a variable to hold one of several types. Use the | symbol. For example:

let value: string | number;
value = "hello";
value = 42;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you create a Readonly object in TypeScript?

A

Use the Readonly utility type to make all properties of an object immutable. For example:

interface User {
  name: string;
  age: number;
}

const user: Readonly<User> = { name: "John", age: 30 };
// user.name = "Jane"; // Error: Cannot assign to 'name'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do enums work in TypeScript?

A

Enums define a set of named constants. Use enum. For example:

enum Color {
  Red,
  Green,
  Blue,
}

let c: Color = Color.Green;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is a mapped type in TypeScript?

A

Mapped types create new types by transforming properties of an existing type. For example:

type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are type guards in TypeScript?

A

Type guards are functions or constructs that allow you to narrow types during runtime checks. For example:

function isString(value: any): value is string {
  return typeof value === "string";
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the never type in TypeScript?

A

The never type represents values that never occur, often used in unreachable code. For example:

function throwError(message: string): never {
  throw new Error(message);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How can you mark a function parameter as optional in TypeScript?

A

Add a ? after the parameter name. Example: function greet(name?: string) {}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the benefit of using optional parameters in TypeScript?

A

It allows functions to be called without providing all arguments, preventing unnecessary TypeScript errors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

If we’d like to be explicit about what type a function returns, how can we do this with type script?

A

We can add an explicit type annotation after its closing parenthesis.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Why does TypeScript infer boolean[] instead of a fixed-length tuple like [boolean, boolean, boolean] for an array initialized as \[true, false, false]?

A

boolean[] is less restrictive, allowing for the addition of more boolean elements to the array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How does TypeScript infer the type of a new array created using the .concat() method with a tuple and another array?

A

TypeScript infers the result as a standard array of the combined element types, not a tuple.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How do you define an array of tuples?

A

You define an array of tuples in TypeScript by specifying an array ([]) where each element within that array conforms to a specific tuple type. The tuple type itself is defined by enclosing the types of its elements in square brackets [].

let arrayOfTuples: [Type1, Type2, ...][] = [/* ... array of [Type1, Type2, ...] elements ... */];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How does TypeScript’s spread syntax interact effectively with tuples, and in what scenario is this particularly useful?

A

TypeScript’s spread syntax (…) can be used to pass the elements of a tuple as individual arguments to a function. This is most useful for function calls that expect a specific number and type of arguments, perfectly matching the structure of a tuple.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Provide the general syntax demonstrating how TypeScript's spread syntax can be used to pass the elements of a tuple as arguments to a function.
**Tuple Definition:** ``` let myTuple: [Type1, Type2, Type3] = [value1, value2, value3]; ``` **Function Definition:** ``` function myFunction(arg1: Type1, arg2: Type2, arg3: Type3): void { // Function body using arg1, arg2, arg3 console.log(arg1, arg2, arg3); } ``` **Using Spread Syntax with Tuple in Function Call:** ``` myFunction(...myTuple); ```
25
Which of the following function calls will produce a Type Error for this function? ``` const range = (...myData: number[]) => { myData.sort(); return myData[myData.length - 1] - myData[0]; } ``` A) range([3, 7, 5]); B) range(); C) range(1); D) range(3, 7, 5);
A: ✅ A) range([3, 7, 5]); This produces a Type Error because it passes an array, but the function expects individual numbers due to the rest parameter (...myData: number[]). The other calls are valid.
26
What does the rest parameter syntax (...paramName) do in a function signature?
It gathers zero or more arguments passed to the function into a single array named paramName.
27
How do you specify the type of elements collected by a rest parameter in TypeScript (e.g. for numbers)?
You add an array type annotation after the parameter name: ...myNumbers: **number[]**. This means each individual argument passed must be compatible with number.
28
Why does calling range([1
2
29
Does calling range() cause a type error for const range = (...nums: number[]) => { ... }? Why or why not?
No type error. Rest parameters explicitly allow zero arguments. nums simply becomes an empty array []. (It might cause a runtime error inside the function if it tries to access elements like nums[0]).
30
What is the main purpose of using generic types (like Array) in TypeScript?
To create reusable components (types, functions, classes) that can work with multiple different types while maintaining type safety. T acts as a placeholder for a specific type.
31
What are the two equivalent ways to declare a variable as an array of strings in TypeScript?
1. Generic syntax: **Array**
2. Shorthand syntax: **string[]**
They mean the exact same thing.
32
What is a key benefit of explicitly typing an array (e.g., let names: string[] = [...])?
Type Safety: TypeScript checks at compile time that only elements of the specified type (string in this case) are added, and knows the type of elements retrieved. Also improves readability.
33
What does the type any[] signify?
It represents an array ([]) where the elements within it can be of any type (any). It doesn't restrict element types or their order (beyond being in an array).
34
What is an enum in TypeScript?
A special type used to define a set of named constant values.
35
Why use enums in TypeScript?
To restrict a variable to only a limited set of possible values.
36
What does the following code define? `enum Direction { North, South, East, West }`
An enum named Direction with four possible values: North, South, East, and West.
37
What is the correct way to reference the West value of the Direction enum?
Direction.West
38
What is the numeric value of `Direction.East` in `enum Direction { North, South, East, West }`?
2
39
Can you assign a number directly to a variable of an enum type?
Yes. Numbers can be directly assigned since enum values are numbers under the hood.
40
What happens if you assign `whichWayToArcticOcean = 2` when using `enum Direction`?
It is valid and sets the variable to Direction.East, since East is 2.
41
How can you change the starting number for enum values?
By assigning a value to the first member, like `enum Direction { North = 7, ... }`
42
What are the values of `Direction` in `enum Direction { North = 7, South, East, West }`?
North = 7, South = 8, East = 9, West = 10
43
Can you manually assign all numeric values in a TypeScript enum?
Yes. For example: `enum Direction { North = 8, South = 2, East = 6, West = 4 }`
44
How does TypeScript store enum values under the hood?
As numbers corresponding to their declaration order or assigned values.
45
Can enum types be used in type annotations like other types?
Yes. For example: `let dir: Direction;`
46
What are the two types of enums in TypeScript?
Numeric enums and string enums.
47
What is a numeric enum in TypeScript?
An enum where members are assigned auto-incrementing numbers.
48
What is a string enum in TypeScript?
An enum where members are explicitly assigned string values.
49
How are string enums declared in TypeScript?
`enum Direction { North = 'NORTH', South = 'SOUTH', ... }`
50
Can numeric enums be auto-assigned?
Yes, numeric values are auto-incremented starting from 0 unless specified otherwise.
51
Can string enums be auto-assigned?
No, all string values must be explicitly assigned.
52
Why is it better to use strings like North = 'NORTH' instead of random strings in string enums?
It improves readability and makes error messages and logs more informative.
53
Can you assign a number directly to a numeric enum variable?
Yes, even arbitrary numbers like `943205` will not throw a TypeScript error.
54
What is a risk of using numeric enums?
Bugs can sneak in because any number can be assigned without error.
55
Can you assign a string directly to a string enum variable?
No, this will cause a TypeScript type error.
56
How must a string enum value be assigned?
Only using the enum itself, e.g., `DirectionString.South`.
57
Which enum type is stricter: string or numeric?
String enums are stricter.
58
Which enum type is more recommended in TypeScript?
String enums, because they prevent unintended assignments and are more readable.
59
What is a type alias in TypeScript?
A custom name for any type, defined using the `type` keyword.
60
How do you define a type alias?
Using the format: `type AliasName = Type;`
61
What is the benefit of using type aliases?
They reduce repetition and improve code readability, especially for complex types.
62
Can you use a type alias with primitive types?
Yes, e.g., `type MyString = string;`
63
What is a more practical use case for type aliases?
Defining aliases for object types or tuples used repeatedly in code.
64
What is an example of a useful type alias for a person object?
`type Person = { name: string, age: number };`
65
How can type aliases reduce duplication in object definitions?
By reusing the alias instead of rewriting the full object shape every time.
66
Do type aliases change how TypeScript types behave?
No. Aliases are just alternate names and don’t create new types.
67
Are `type MyString = string` and `type MyOtherString = string` considered different types?
No, they are treated as the same type since both alias `string`.
68
Can variables of different aliases based on the same type be assigned to each other?
Yes, because they point to the same base type.
69
What is the key takeaway about type aliases?
They simplify your code but do not affect type behavior at all.
70
What is a function type in TypeScript?
A type that specifies the argument types and return type of a function.
71
How do you define a function type that takes two strings and returns a number?
```type StringsToNumberFunction = (arg0: string, arg1: string) => number;```
72
Can parameter names be different when assigning functions to a function type?
Yes, only the **types** matter, not the **names** of the parameters.
73
Can you omit parameter names or parentheses in function type annotations?
No. You must include both parameter names and parentheses, even for one parameter.
74
What is the correct format for a function type with one string parameter and number return?
`(arg: string) => number`
75
What is a practical use case for function types in TypeScript?
Typing **callback functions** for higher-order functions or event handlers.
76
Can you assign different functions to the same function-typed variable?
Yes, as long as they match the expected parameter and return types.