0
0
Typescriptprogramming~10 mins

Distributive conditional types in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a conditional type that returns 'string' if T is 'string', otherwise 'number'.

Typescript
type CheckType<T> = T extends [1] ? 'string' : 'number';
Drag options to blanks, or click blank then click option'
Astring
Bnumber
Cboolean
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'number' instead of 'string' in the extends clause.
Confusing the order of true and false branches.
2fill in blank
medium

Complete the code to create a distributive conditional type that extracts the element type from an array type.

Typescript
type ElementType<T> = T extends [1] ? T[number] : T;
Drag options to blanks, or click blank then click option'
Aany[]
Bobject
Creadonly any[]
DArray<any>
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Array' instead of 'any[]' which may cause distributive behavior issues.
Not using T[number] to extract element type.
3fill in blank
hard

Fix the error in the conditional type that should distribute over union types to return 'true' if T is 'string' or 'number', otherwise 'false'.

Typescript
type IsStringOrNumber<T> = T extends [1] ? true : false;
Drag options to blanks, or click blank then click option'
Astring | boolean
Bstring | number
Cnumber | boolean
Dboolean
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string | boolean' which excludes 'number'.
Using only 'string' or 'number' alone, missing the union.
4fill in blank
hard

Fill both blanks to create a conditional type that returns the keys of T whose values extend string.

Typescript
type StringKeys<T> = { [K in keyof T]: T[K] [1] string ? K : never }[[2]];
Drag options to blanks, or click blank then click option'
Aextends
Bkeyof T
CT
Din
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'in' instead of 'extends' in the conditional check.
Using 'T' instead of 'keyof T' in the final index.
5fill in blank
hard

Fill all three blanks to create a distributive conditional type that converts union members to their array types, otherwise returns never.

Typescript
type ToArray<T> = T extends [1] ? [2][] : [3];
Drag options to blanks, or click blank then click option'
Aany
BT
Cnever
Dunknown
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'any' instead of 'unknown' which may affect distributive behavior.
Returning 'T' instead of 'T[]' for the true branch.