Property does not exist on type

// Solution 1: The Quick Fix
// In TypeScript, we can type a function by specifying the parameter types and return types.

// Similarly, we need to type our objects, so that TypeScript knows what is and isn’t allowed for our keys and values.

// 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.

let obj: any = {}
obj.key1 = 1;
obj['key2'] = 'dog';

//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?

// Well, that’s why there’s the proper fix.

// Solution 2: The Proper Fix
// 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.

interface ExampleObject {
    [key: string]: any
}
let obj: ExampleObject = {};
obj.key1 = 1;
obj['key2'] = 'dog';

// What if this interface is only used once?
// We can make our code a little more concise with the following:

let obj: {[k: string]: any} = {};
obj.key1 = 1;
obj['key2'] = 'dog';
Solution 3: The JavaScript Fix

// Pure JavaScript. What if we don’t want to worry about types?
// Well, don’t use TypeScript ;)

// Or you can use Object.assign().

let obj = {};
Object.assign(obj, {key1: 1});
Object.assign(obj, {key2: 'dog'});

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source