Answers for "property 'find' does not exist on type 'htmlelement'"

4

Property 'value' does not exist on type 'HTMLElement'.

document.getElementById() returns the type HTMLElement which does not contain a value property.
The subtype HTMLInputElement does however contain the value property.

So a solution is to cast the result of getElementById() to HTMLInputElement like this:

var inputValue = (<HTMLInputElement>document.getElementById(elementId)).value;
<> is the casting operator in typescript.
See TypeScript: casting HTMLElement: https://fireflysemantics.medium.com/casting-htmlelement-to-htmltextareaelement-in-typescript-f047cde4b4c3

The resulting javascript from the line above looks like this:

inputValue = (document.getElementById(elementId)).value;
i.e. containing no type information.
Posted by: Guest on October-17-2020
2

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'});
Posted by: Guest on August-09-2021

Code answers related to "property 'find' does not exist on type 'htmlelement'"

Code answers related to "TypeScript"

Browse Popular Code Answers by Language