1// Solution 1: The Quick Fix
2// In TypeScript, we can type a function by specifying the parameter types and return types.
3
4// Similarly, we need to type our objects, so that TypeScript knows what is and isn’t allowed for our keys and values.
5
6// Quick and dirty. A quick and dirty way of doing this is to assign the object to type any. This type is generally used for dynamic content of which we may not know the specific type. Essentially, we are opting out of type checking that variable.
7
8let obj: any = {}
9obj.key1 = 1;
10obj['key2'] = 'dog';
11
12//But then, what’s the point of casting everything to type any just to use it? Doesn’t that defeat the purpose of using TypeScript?
13
14// Well, that’s why there’s the proper fix.
15
16// Solution 2: The Proper Fix
17// Consistency is key. In order to stay consistent with the TypeScript standard, we can define an interface that allows keys of type string and values of type any.
18
19interface ExampleObject {
20 [key: string]: any
21}
22let obj: ExampleObject = {};
23obj.key1 = 1;
24obj['key2'] = 'dog';
25
26// What if this interface is only used once?
27// We can make our code a little more concise with the following:
28
29let obj: {[k: string]: any} = {};
30obj.key1 = 1;
31obj['key2'] = 'dog';
32Solution 3: The JavaScript Fix
33
34// Pure JavaScript. What if we don’t want to worry about types?
35// Well, don’t use TypeScript ;)
36
37// Or you can use Object.assign().
38
39let obj = {};
40Object.assign(obj, {key1: 1});
41Object.assign(obj, {key2: 'dog'});
42