Currently, I am delving into TypeScript by following an online tutorial. While my programming background primarily consists of 'structurally' typed languages like C and ActionScript 3, TypeScript presents some new concepts for me to grasp.
One particular aspect that I'm focusing on is the 'dictionary' type of Object.
interface dict {
[accessString: string]: {
name: string;
address: string
} | undefined
}
To clarify, an object adhering to this interface will allow access through code snippets like:
const userData = myObject['someString']
const userData2 = myObject.someString
In this scenario, both userData
and userData2
would reference the same object with the fields name
and address
. If the field does not exist, it returns undefined
, hence including | undefined
in the interface definition.
Now, how does this differ conceptually from defining an object interface as follows?
interface notDict {
someString: {
name: string;
address: string
}
The difference lies in the certainty about the existence of the field someString
in the object. Whereas, in the original 'dictionary-type' definition, we leave room for ambiguity regarding the fields. Are there any other distinctions between the [accessString:string]:{}
definition and a plain object
definition that I may be overlooking?
I appreciate any insights you can provide!