0
0
Typescriptprogramming~20 mins

Conditional type with generics in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Conditional Type Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of conditional type with string generic
What is the output of the following TypeScript code when TestType<'hello'> is used?
Typescript
type TestType<T> = T extends string ? 'string type' : 'other type';

const result: TestType<'hello'> = 'string type';
console.log(result);
A"other type"
B"string type"
CType error: Type 'string' is not assignable to 'other type'
Dundefined
Attempts:
2 left
💡 Hint
Check if the generic type extends string or not.
Predict Output
intermediate
2:00remaining
Conditional type with union generic
What is the type of Result in the code below?
Typescript
type Conditional<T> = T extends number ? 'number' : 'not number';
type Result = Conditional<string | number>;

// What is Result?
A"number" | "not number"
B"number"
C"not number"
Dstring | number
Attempts:
2 left
💡 Hint
Conditional types distribute over unions.
🔧 Debug
advanced
2:00remaining
Why does this conditional type cause an error?
Identify the error in this TypeScript code and what error it produces.
Typescript
type Check<T> = T extends { id: number } ? T : never;

const obj: Check<{ name: string }> = { name: 'Alice' };
AType error: Type '{ name: string; }' is not assignable to type 'never'.
BSyntax error: Missing semicolon.
CNo error, code compiles fine.
DRuntime error: Property 'id' is undefined.
Attempts:
2 left
💡 Hint
Check what happens when the generic type does not extend the condition.
📝 Syntax
advanced
2:00remaining
Which option correctly defines a conditional generic type?
Choose the option that correctly defines a conditional type with generics to check if T is assignable to string.
Atype IsString<T> = T ? string : false;
Btype IsString<T> = if T extends string then true else false;
Ctype IsString<T> = T extends string ? 'yes';
Dtype IsString<T> = T extends string ? true : false;
Attempts:
2 left
💡 Hint
Look for correct TypeScript conditional type syntax.
🚀 Application
expert
3:00remaining
What is the output of this complex conditional generic type?
Given the code below, what is the type of Result?
Typescript
type Flatten<T> = T extends Array<infer U> ? U : T;

type Result = Flatten<string[] | number>;
Anever
Bstring[] | number
Cstring | number
Dstring
Attempts:
2 left
💡 Hint
Remember conditional types distribute over unions and infer extracts the array element type.