0
0
Typescriptprogramming~10 mins

How structural typing differs from nominal typing 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 an interface named Person.

Typescript
interface [1] {
  name: string;
  age: number;
}
Drag options to blanks, or click blank then click option'
ACustomer
BPerson
CEmployee
DUser
Attempts:
3 left
💡 Hint
Common Mistakes
Using a name unrelated to the data structure.
2fill in blank
medium

Complete the code to create a variable with the Person type.

Typescript
const user: [1] = {
  name: 'Alice',
  age: 30
};
Drag options to blanks, or click blank then click option'
ACustomer
BUser
CEmployee
DPerson
Attempts:
3 left
💡 Hint
Common Mistakes
Using a type name that was not declared.
3fill in blank
hard

Fix the error in the function parameter type to accept any object with name and age.

Typescript
function greet(person: [1]) {
  console.log(`Hello, ${person.name}!`);
}
Drag options to blanks, or click blank then click option'
A{ name: string; age: number }
BUser
CPerson
DEmployee
Attempts:
3 left
💡 Hint
Common Mistakes
Using a nominal type that may not match the object.
4fill in blank
hard

Fill both blanks to create two types and check if they are compatible structurally.

Typescript
type [1] = { id: number };
type [2] = { id: number; name: string };

const a: [1] = { id: 1 };
const b: [2] = { id: 2, name: 'Bob' };

const c: [1] = b; // Allowed because of structural typing
Drag options to blanks, or click blank then click option'
AID
BUser
CPerson
DEmployee
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing nominal typing with structural typing.
5fill in blank
hard

Fill all three blanks to demonstrate nominal typing using classes and type compatibility.

Typescript
class [1] {
  constructor(public id: number) {}
  private __brand[1]: void;
}

class [2] {
  constructor(public id: number, public name: string) {}
  private __brand[2]: void;
}

const x: [1] = new [2](1, 'Carol'); // Error in nominal typing
Drag options to blanks, or click blank then click option'
AID
BUser
CPerson
DEmployee
Attempts:
3 left
💡 Hint
Common Mistakes
Assuming structural typing applies to classes.