0
0
Typescriptprogramming~10 mins

Readonly utility type 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 make the object properties read-only using the Readonly utility type.

Typescript
type User = [1]<{ name: string; age: number }>;
Drag options to blanks, or click blank then click option'
AReadonly
BPartial
CRequired
DRecord
Attempts:
3 left
💡 Hint
Common Mistakes
Using Partial instead of Readonly, which makes properties optional, not read-only.
Using Required which makes properties mandatory but does not affect mutability.
2fill in blank
medium

Complete the code to create a read-only object and try to assign a new value to a property (which should cause an error).

Typescript
const user: Readonly<{ name: string }> = { name: 'Alice' };
user.[1] = 'Bob';
Drag options to blanks, or click blank then click option'
Aname
Blength
CtoString
Dage
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to assign to a property that does not exist.
Confusing method names with property names.
3fill in blank
hard

Fix the error in the code by using the Readonly utility type correctly.

Typescript
interface Config {
  url: string;
  timeout: number;
}

const config: [1]<Config> = {
  url: 'https://api.example.com',
  timeout: 5000
};

config.timeout = 3000;
Drag options to blanks, or click blank then click option'
APick
BPartial
CReadonly
DRecord
Attempts:
3 left
💡 Hint
Common Mistakes
Using Partial which makes properties optional but not read-only.
Using Pick or Record which do not make properties read-only.
4fill in blank
hard

Fill both blanks to create a read-only array of strings and try to push a new element (which should cause an error).

Typescript
const fruits: [1]<string[]> = ['apple', 'banana'];
fruits.[2]('orange');
Drag options to blanks, or click blank then click option'
AReadonly
Bpush
Cpop
DPartial
Attempts:
3 left
💡 Hint
Common Mistakes
Using Partial instead of Readonly.
Using pop instead of push to add elements.
5fill in blank
hard

Fill all three blanks to define a read-only object type, create an instance, and attempt to modify a property (which should cause an error).

Typescript
type [1]<T> = {
  readonly [P in keyof T]: T[P];
};

interface Person {
  name: string;
  age: number;
}

const person: [2]<Person> = { name: 'John', age: 25 };
person.[3] = 30;
Drag options to blanks, or click blank then click option'
AReadonly
Cage
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'name' instead of 'age' for the property to modify.
Not using the Readonly type for the variable.