0
0
Typescriptprogramming~10 mins

Union vs intersection mental model in Typescript - Interactive Practice

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

Complete the code to declare a variable that can be a string or a number using a union type.

Typescript
let value: string [1] number;
Drag options to blanks, or click blank then click option'
A/
B&
C|
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using & instead of | for union types
Using + or / which are not type operators
2fill in blank
medium

Complete the code to declare a type that combines two interfaces using an intersection.

Typescript
type Person = Name [1] Age;
Drag options to blanks, or click blank then click option'
A&
B+
C|
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using | instead of & for intersection types
Using arithmetic operators like + or -
3fill in blank
hard

Fix the error in the function parameter type to accept either a string or number using union.

Typescript
function printValue(value: string [1] number) { console.log(value); }
Drag options to blanks, or click blank then click option'
A&
B|
C,
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using & which means intersection, not union
Using commas or slashes which are invalid here
4fill in blank
hard

Fill both blanks to create a type that is either a string or a number and also has a length property.

Typescript
type StringOrNumberWithLength = (string [1] number) [2] { length: number };
Drag options to blanks, or click blank then click option'
A|
B&
C+
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up union and intersection operators
Using arithmetic operators instead of type operators
5fill in blank
hard

Fill all three blanks to create a function that accepts either a string or number and returns an object with the value and its type.

Typescript
function describeValue(value: string [1] number): { val: [2], type: string } { return { val: value, type: typeof value }; }
Drag options to blanks, or click blank then click option'
A&
Bstring | number
D|
Attempts:
3 left
💡 Hint
Common Mistakes
Using & instead of | for union types
Not matching the return type val with the parameter type