TS Utility Types Flashcards

Learn what TS Utility Types are, what they do, and how to "spot the error" in a code snippet example. (26 cards)

1
Q

Spot the error in the following code snippet:

type Status = "open" | "closed" | "pending";
// AI wants to remove "pending"
type ActiveStatus = Omit<Status, "pending">;
A

The Error: Wrong Utility.
Omit is for Object keys.
For Unions, you must use Exclude.

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

Spot the error in the following code snippet:

async function getCount() { return 5; }
// AI wants to type a variable to hold the result
const result: ReturnType<typeof getCount> = 10;
A

The Error: Unwrapped Promise.

ReturnType of an async function is Promise, not number. What’s actually returned:

Promise<number>

Instead, it should be “Awaited” like this:

Awaited<ReturnType<typeof getCount>>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Spot the error in the following code snippet:

class Logger { constructor(mode: string) {} }
type Args = ConstructorParameters<Logger>;
A

The Error: Missing typeof.

Logger refers to the instance. To get the constructor parameters, you must use typeof Logger. So, code to right of Args should be:

ConstructorParameters<typeof Logger>;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Spot the error in the following code snippet:

type Input = string | null | undefined;
type ValidatedInput = NonNullable<Input>;
// AI says ValidatedInput ensures the string isn't empty ("")
A

The Error: Conceptual Misunderstanding.

NonNullable only removes null and undefined. An empty string ” “ (space added for display reasons only), is still a valid string and will pass through.
So, you must check if string is empty to truly ensure input is validated.

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

Spot the error in the following code snippet:

// AI wants an object where keys are numbers and values are strings
type MyDict = Record<string, number>;
const data: MyDict = { 1: "Hello" };
A

The Error: Argument Order.

Record takes in a key and value type between the less-than and greater-than symbols, like this:

Record<K, T> // Official syntax
// Could also be thought of in another syntax
Record<Keys, Values>

The AI swapped them. It should be:

Record<number, string>

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

Scenario: The AI wants to create a type that only includes “red” from a union.

type Colors = "red" | "blue" | "green";
type OnlyRed = Pick<Colors, "red">;

Is this correct? If not, why?

A

Verdict: Incorrect.
The Reason: Pick and Omit are for Object properties (keys). They do not work on Unions (for the type).

The Fix: Use Extract.

type OnlyRed = Extract<Colors, "red">;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Scenario: The AI wants to ensure a User update contains every property, including optional ones.

type User = { id: number; name?: string; email?: string };

const update: Required<User> = { 
  id: 1, 
  name: "John" 
};

Will this compile?

A

Verdict: No.

The Reason:

Required<T>

The Required utility type makes every property mandatory.

Since email was optional in the original type, it is now required in the new type. The AI forgot email.

The Fix: Either add email to the object or use

Pick<Required<User>, 'id' | 'name'>

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

Scenario: The AI tries to extract a type that doesn’t exist in the union.

type Result = Extract<string | number, boolean>;

Does TypeScript throw an error here? What is the value of Result?

A

Verdict: No error. The value is “never”.

The Reason: Extract filters for matches.
If there is no overlap between the two types, the result is an empty set, which TypeScript represents as the “never” type.

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

Scenario: The AI is trying to access a static method on an instance type.

class Logger {
  static logVersion() { console.log("1.0") }
  save() { console.log("Saved") }
}

type AppLogger = InstanceType<typeof Logger>;
// AI says AppLogger includes 'logVersion'

Is the AI correct?

A

Verdict: Incorrect.

The Reason: InstanceType only includes members of the instance (things available after calling new).
Static members belong to the Class constructor itself, not the instance.

AppLogger is equivalent to an interface containing only the non-static parts. Meaning,
“AppLogger” only has the save() method.

// literal value of AppLogger
type AppLogger = { save: () => void; }

It excludes logVersion because that belongs to the “Constructor,” not the “Instance.”

Why this matters for an Evaluator:
AI models often try to use InstanceType to “copy” a class entirely, including its static helpers.
You need to flag that InstanceType only gives you the shape of the object created by new.

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

Scenario: The AI wants to get the type of the first argument of this function.

function setRole(id: number, role: "admin" | "user") {}

type RoleType = Parameters<typeof setRole>[1];

Did the AI successfully get the type for id?

A

Verdict: No.
The Reason: Parameters returns a Tuple (an array).
Like all arrays in JavaScript, it is zero-indexed.
Index [1] is the second argument (“admin” | “user”).

The Fix: Use the Parameters Utility to get the type for id.

Parameters<typeof setRole>[0]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Partial<T></T>

A

Makes all properties in an object optional.
* Logic: { K?: T[K] }
* Use Case: Updating only specific fields of a user profile.

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

Required<T></T>

A

Makes all properties in an object mandatory (the opposite of Partial).
* Logic: Removes the ? from all keys.
* Use Case: Ensuring a configuration object is fully populated before use.

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

Readonly<T></T>

A

Makes all properties immutable (read-only) at compile-time.
* Logic: Prepends readonly to every key.
* Use Case: Preventing accidental state mutations in React props.

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

Record<K, V>

A

Constructs an object type with specific Keys and a specific Value type.
* Logic: K is the property name type, V is the property value type.
* Use Case: Creating a dictionary or a map (e.g., Record<string, User>).

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

Pick<T, K>

A

Creates a new type by selecting specific keys from an object.
* Target: Objects/Interfaces.
* Use Case: Passing only a subset of data (e.g., just id and name) to a child component.

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

Omit<T, K>

A

Creates a new type by removing specific keys from an object.
* Target: Objects/Interfaces.
* Use Case: Creating a “UserWithoutPassword” type by removing the password key.

17
Q

Exclude<Union, Members>

A

Removes specific members from a Union type.
* Logic: Keeps everything that doesn’t match the criteria.
* Target: Unions (not Objects).

18
Q

Extract<Union, Members>

A

Keeps only the specific members from a Union that match the criteria.
* Logic: Filters the union for matches.
* Target: Unions (not Objects).

19
Q

NonNullable<T></T>

A

Removes null and undefined from a type.
* Note: Does not remove empty strings "" or 0.
* Use Case: Cleaning up a type before performing logic that requires a value.

20
Q

Parameters<T></T>

A

Extracts the argument types of a function as a Tuple (array).
* Requirement: Requires typeof before the function name.
* Use Case: Reusing the input types of an existing function for a wrapper.

21
Q

ReturnType<T></T>

A

Extracts the return type of a function.
* Requirement: Requires typeof before the function name.
* Use Case: Getting the shape of data returned by an API helper or library.

22
Q

ConstructorParameters<T></T>

A

Extracts the argument types of a Class Constructor as a Tuple.
* Requirement: Requires typeof before the Class name.
* Use Case: Typing factory functions that create class instances.

23
Q

InstanceType<T></T>

A

Extracts the type of an instance created by a Class.
* Requirement: Requires typeof before the Class name.
* Use Case: Typing variables that hold a “newed up” class object.

24
Q

Awaited<T></T>

A

Recursively “unwraps” a Promise to get the type of the value inside.
* Use Case: Getting the actual data type from an async function’s ReturnType.

25
Uppercase / Lowercase
Converts every character in a **String Literal Union** to upper or lower case. * **Target:** String literals only (not the generic `string` type).
26
Capitalize / Uncapitalize
Converts the **first character** of a string literal to upper or lower case. * **Use Case:** Dynamically generating types for "getters" (e.g., `getName`).