-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path46.IndexSignatures.ts
39 lines (31 loc) · 1.24 KB
/
46.IndexSignatures.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Using Index Signatures in TypeScript
// Define a type for a User with a name and an address.
type User = {
fullName: string;
contact: string;
};
// Define a type for a User Directory using index signatures.
// This allows us to create an object where the keys are strings (representing usernames)
// and the values are of type User or undefined.
type UserDirectory = {
[usernameKey: string]: User | undefined;
};
// Create an instance of the UserDirectory with a sample user.
const users: UserDirectory = {
'alice123': {
fullName: 'Alice Wonderland',
contact: '[email protected]'
},
};
// Accessing a user's full name using their username.
users['alice123']?.fullName; // Alice Wonderland
// Adding a new user to the directory.
users['bob456'] = {fullName: 'Bob Builder', contact: '[email protected]'}
// Displaying the newly added user's details.
console.log(users['bob456']); // { fullName: 'Bob Builder', contact: '[email protected]'}
// Removing a user from the directory using the delete keyword.
delete users['bob456'];
// Trying to access a user that doesn't exist in the directory.
// The result will be of type User | undefined.
const fetchedUser = users['nonexistentUser'];
console.log(fetchedUser); // undefined