0
0
Typescriptprogramming~30 mins

How structural typing differs from nominal typing in Typescript - Try It Yourself

Choose your learning style9 modes available
How structural typing differs from nominal typing
📖 Scenario: Imagine you are organizing a party and you want to check if guests have the right invitation. Invitations can be different but if they have the same important details, they are accepted.
🎯 Goal: You will create two types of invitations using TypeScript: one using structural typing and one using nominal typing. You will see how TypeScript treats them differently when checking if a guest's invitation is valid.
📋 What You'll Learn
Create two interfaces with the same structure
Create two variables with these interfaces
Show how TypeScript allows assignment with structural typing
Show how nominal typing prevents assignment
Print results to demonstrate the difference
💡 Why This Matters
🌍 Real World
Understanding how TypeScript checks types helps you write safer code that avoids bugs caused by mixing incompatible data.
💼 Career
Many software jobs require knowledge of TypeScript's type system to build reliable web applications and APIs.
Progress0 / 4 steps
1
Create two interfaces with the same structure
Create two interfaces called InvitationA and InvitationB. Both should have a name property of type string and a date property of type string.
Typescript
Need a hint?

Interfaces define the shape of an object. Both interfaces should look exactly the same.

2
Create variables with these interfaces
Create a variable called inviteA of type InvitationA with name set to "Alice" and date set to "2024-07-01". Create another variable called inviteB of type InvitationB with name set to "Bob" and date set to "2024-07-02".
Typescript
Need a hint?

Use const to create variables with the given types and values.

3
Show structural typing allows assignment
Assign inviteB to a new variable called structuralTest of type InvitationA. This should work because TypeScript uses structural typing.
Typescript
Need a hint?

Assign inviteB directly to a variable typed as InvitationA.

4
Show nominal typing prevents assignment
Create a type called NominalInvitationA that adds a unique brand to InvitationA to simulate nominal typing. Then try to assign inviteB to a variable nominalTest of type NominalInvitationA. Print structuralTest and nominalTest to show the difference.
Typescript
Need a hint?

Use a branded type to simulate nominal typing. Assigning inviteB directly to NominalInvitationA is not allowed. Print both variables to see the difference.