Bird
Raised Fist0
Typescriptprogramming~20 mins

Generic conditional constraints in Typescript - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Generic Constraints Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of generic function with conditional constraint
What is the output of this TypeScript code when calling processValue(10)?
Typescript
function processValue<T extends number | string>(value: T): string {
  if (typeof value === 'number') {
    return `Number: ${value * 2}`;
  } else {
    return `String: ${value.toUpperCase()}`;
  }
}

console.log(processValue(10));
A"String: 10"
BTypeError at runtime
C"Number: 20"
DCompilation error due to generic constraint
Attempts:
2 left
💡 Hint
Check how the function handles numbers differently from strings.
❓ Predict Output
intermediate
2:00remaining
Result of generic function with conditional type check
What will be logged when calling formatValue('hello') in this TypeScript code?
Typescript
function formatValue<T extends string | boolean>(input: T): string {
  return typeof input === 'string' ? input.toUpperCase() : input ? 'TRUE' : 'FALSE';
}

console.log(formatValue('hello'));
ACompilation error due to generic constraint
B"HELLO"
C"TRUE"
D"hello"
Attempts:
2 left
💡 Hint
Look at how the function treats strings differently from booleans.
🔧 Debug
advanced
2:00remaining
Identify the error in generic conditional constraint usage
What error does this TypeScript code produce?
Typescript
function getLength<T>(item: T): number {
  if (item.length) {
    return item.length;
  }
  return 0;
}

getLength(123);
ACompilation error: Generic constraint missing
BReturns 0 without error
CRuntime error: Cannot read property 'length' of undefined
DCompilation error: Property 'length' does not exist on type 'T'.
Attempts:
2 left
💡 Hint
Check if the generic type T is constrained to have a length property.
📝 Syntax
advanced
2:00remaining
Which option correctly defines a generic function with conditional constraint?
Which of the following TypeScript function signatures correctly constrain generic type T to types that have a 'length' property?
Afunction example<T extends { length: number }>(arg: T): number;
Bfunction example<T>(arg: T extends { length: number } ? T : never): number;
Cfunction example<T>(arg: T): T extends { length: number } ? number : never;
Dfunction example<T extends length>(arg: T): number;
Attempts:
2 left
💡 Hint
Look for correct syntax for generic constraints in TypeScript.
🚀 Application
expert
3:00remaining
Determine the output of a complex generic conditional type function
Given the following TypeScript code, what is the output of describeValue([1, 2, 3])?
Typescript
function describeValue<T>(value: T): string {
  type HasLength = T extends { length: number } ? true : false;
  if ((value as any).length !== undefined) {
    return `Length is ${(value as any).length}`;
  } else {
    return 'No length property';
  }
}

console.log(describeValue([1, 2, 3]));
A"Length is 3"
B"No length property"
CCompilation error due to conditional type misuse
DRuntime error: Cannot read property 'length' of undefined
Attempts:
2 left
💡 Hint
Arrays have a length property. The function uses a type alias but checks length at runtime.

Practice

(1/5)
1.

What does a generic conditional constraint in TypeScript allow you to do?

For example, in function example(arg: T) {}, what is the main purpose?

easy
A. Control the generic type based on a condition to improve type safety
B. Make the function run faster by optimizing loops
C. Automatically convert types to strings
D. Disable type checking for the generic parameter

Solution

  1. Step 1: Understand generic conditional constraints

    Generic conditional constraints let you choose a type based on a condition, like T extends U ? X : Y.
  2. Step 2: Identify the purpose in the example

    This controls the generic type to be either X or Y depending on whether T extends U, improving type safety.
  3. Final Answer:

    Control the generic type based on a condition to improve type safety -> Option A
  4. Quick Check:

    Generic conditional constraints = control type conditionally [OK]
Hint: Think: conditional means choosing type based on a test [OK]
Common Mistakes:
  • Confusing conditional constraints with runtime conditions
  • Thinking it affects performance instead of types
  • Assuming it disables type checking
2.

Which of the following is the correct syntax for a generic conditional constraint in TypeScript?

function test<T>(arg: T extends string ? number : boolean) {}
easy
A. function test<T>(arg: T extends string ? number : boolean) {}
B. function test(arg: T) {}
C. function test(arg: T) {}
D. function test<T>(arg: T) where T extends string ? number : boolean {}

Solution

  1. Step 1: Identify correct generic conditional syntax

    The conditional type must be used in the argument type, not in the generic constraint part.
  2. Step 2: Check each option

    function test<T>(arg: T extends string ? number : boolean) {} correctly places the conditional type in the argument type: arg: T extends string ? number : boolean.
  3. Final Answer:

    function test<T>(arg: T extends string ? number : boolean) {} -> Option A
  4. Quick Check:

    Conditional type goes in argument type, not generic constraint [OK]
Hint: Conditional types appear in argument or return types, not in generic constraints [OK]
Common Mistakes:
  • Putting conditional directly in generic constraint
  • Using invalid syntax like 'where'
  • Misplacing parentheses in conditional
3.

What is the output of this TypeScript code?

type Result<T> = T extends number ? "Number" : "Other";

const a: Result<42> = "Number";
const b: Result<string> = "Other";

console.log(a, b);
medium
A. 42 string
B. Number Other
C. Number Number
D. Other Other

Solution

  1. Step 1: Understand the conditional type Result<T>

    If T is a number, Result<T> is "Number", else "Other".
  2. Step 2: Apply to given values

    Result<42> is "Number" because 42 is a number.
    Result<string> is "Other" because string is not a number.
  3. Final Answer:

    Number Other -> Option B
  4. Quick Check:

    Conditional type matches number = "Number", else "Other" [OK]
Hint: Check if type extends number to pick output string [OK]
Common Mistakes:
  • Confusing value 42 with type number
  • Assuming string extends number
  • Mixing up output strings
4.

Identify the error in this TypeScript code using generic conditional constraints:

function checkType<T>(value: T): T extends string ? number : boolean {
  if (typeof value === "string") {
    return value.length;
  } else {
    return true;
  }
}
medium
A. Function lacks explicit return type annotation
B. The function parameter should be a union type
C. The generic constraint is missing
D. Cannot return different types conditionally without type assertion

Solution

  1. Step 1: Analyze return type conditionality

    The return type depends on T, but at runtime TypeScript cannot guarantee which type is returned.
  2. Step 2: Understand why error occurs

    Returning value.length (number) or true (boolean) causes a type error because TypeScript can't confirm the return matches the conditional type without assertions.
  3. Final Answer:

    Cannot return different types conditionally without type assertion -> Option D
  4. Quick Check:

    Conditional return types need type assertions or overloads [OK]
Hint: Conditional return types need type assertions to avoid errors [OK]
Common Mistakes:
  • Assuming TypeScript infers conditional return types automatically
  • Adding generic constraints unnecessarily
  • Changing parameter types instead of fixing return
5.

Given this TypeScript code, what is the type of result?

type ConditionalType<T> = T extends { id: number } ? string : number;

function processItem<T>(item: T): ConditionalType<T> {
  if ("id" in item) {
    return "Has ID" as ConditionalType<T>;
  } else {
    return 0 as ConditionalType<T>;
  }
}

const result = processItem({ id: 123, name: "Test" });
hard
A. string | number
B. number
C. string
D. boolean

Solution

  1. Step 1: Understand the conditional type ConditionalType<T>

    If T has an id property of type number, the type is string, else number.
  2. Step 2: Apply to the argument type

    The argument { id: 123, name: "Test" } has an id property of type number, so ConditionalType<T> is string.
  3. Final Answer:

    string -> Option C
  4. Quick Check:

    Object with id:number means ConditionalType = string [OK]
Hint: Check if type has id:number to pick string type [OK]
Common Mistakes:
  • Thinking result is number because of return 0
  • Assuming union type without checking condition
  • Ignoring the conditional type logic
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard