0
0
Typescriptprogramming~10 mins

Phantom 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 declare a phantom type parameter in a TypeScript interface.

Typescript
interface Box<[1]> {
  value: string;
}
Drag options to blanks, or click blank then click option'
AT
Bstring
Cnumber
Dboolean
Attempts:
3 left
💡 Hint
Common Mistakes
Using a concrete type like 'number' instead of a generic type parameter.
Forgetting to declare a generic parameter.
2fill in blank
medium

Complete the code to define a phantom type in a TypeScript type alias.

Typescript
type TaggedString<[1]> = string & { __tag?: [1] };
Drag options to blanks, or click blank then click option'
Anumber
Bboolean
Cstring
DTag
Attempts:
3 left
💡 Hint
Common Mistakes
Using a concrete type like 'string' instead of a generic parameter.
Not using a generic parameter at all.
3fill in blank
hard

Fix the error in the phantom type usage by completing the generic parameter.

Typescript
function wrapValue<[1]>(value: string): TaggedString<[1]> {
  return value as TaggedString<[1]>;
}
Drag options to blanks, or click blank then click option'
Anumber
Bstring
CT
Dboolean
Attempts:
3 left
💡 Hint
Common Mistakes
Using a concrete type like 'string' instead of a generic parameter.
Omitting the generic parameter declaration.
4fill in blank
hard

Fill both blanks to create a phantom type that distinguishes between UserId and OrderId.

Typescript
type [1] = TaggedString<'UserId'>;
type [2] = TaggedString<'OrderId'>;
Drag options to blanks, or click blank then click option'
AUserId
Bstring
COrderId
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the type names and tags.
Using concrete types like 'string' or 'number' instead of phantom types.
5fill in blank
hard

Fill all three blanks to define a function that accepts only UserId and returns a string.

Typescript
function getUserName(id: [1]): [2] {
  // pretend to fetch user name
  return 'User_' + id as [3];
}
Drag options to blanks, or click blank then click option'
AOrderId
Bstring
CUserId
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Using OrderId instead of UserId as parameter type.
Returning a phantom type instead of a string.