Property does not exist ошибка

Property does not exist on type '{}' in TypeScript

The “Property does not exist on type ‘{}’” error occurs in typescript when you try to modify, set or access an object property that does not exist. For example, if you have an object with only two properties and you try to access a third property that’s not contained in the object type. You can fix the above error by explicitly adding the object property or use a variable of the same type or key names. You can bypass or override TypeScript type checking whenever preferable, because is not strictly to be used but I do suggest that you don’t do this often when building a big project. Doing it too much will throw a typescript error “Property does not exist on type ‘object’”

Below is what causes the above error and why it occurs.

const object1 = {};
// accessing property not defined in the above object will throw an error
// Error: Property 'name' does not exist on type '{}'.ts(2339)
object1.name = 'Justice';

From the above, suppose the ‘object1’ is a JSON data that is coming from a particular API (application programming interface) as a result of an HTTP request made when we run the application. Because you didn’t define the object yourself, what you can do with it is to read only the available properties. We have an empty object already defined, therefore we cannot assign values or access properties that does not exist on the object type.

If you know all the required object properties, you can define the object explicitly and include all the properties you do want to access.

// Explicitly define the object type when you know all required property names
type Student = {
  id?: number;
  name?: string;
};
const obj: Student = {};
obj.id = 1;
obj.name = 'John Doe';

// Define the object type like below when you don't know ALL property names 
type Student2 = {
// Define a variable key (you can research how it work if you don’t have any idea)
// what do note is that the variable does not have a particular name.
  [key: string]: any; 
  name: string;
};

const obj2: Student2 = {
  name: 'James',
};
obj2.program = “TypeScript”;

The above first example illustrate how to define an object when you know all of it required property names and types of value that will be assign to it. Note that we were able to create a new empty object ‘obj’ of ‘Student’ because we marked all the object properties as optional with the question-mark symbol ‘?’ (it can be provided or remain null by default). That way, we can initialize the object as empty and later assign value to its properties, that’s the concept you need to understand.

We have included all the needed properties, therefore we will not get the “Property does not exist on type {}” error again when we access any of it because they all exist in the object. So, the key concept to note once again is that computers don’t lie and whenever you encounter such type of error, it means some adjustment needs to be done in your code. 

If you don’t know the type of key, values, shape or structure of your object’s ahead of time, you have to use what’s called index signature as show below.

// Define the object type like below when you don't know ALL property names 
type Student2 = {
// Define a variable key (you can research how it work if you don’t have any idea)
// what do note is that the variable does not have a particular name.
  [key: string]: any; 
  name: string;
};

const obj2: Student2 = {
  name: 'James',
};
obj2.program = “TypeScript”;

Note that the first object property above has been declared as '{[key: string]: any}' with the index signature syntax.  Remember to use this syntax when you don’t know how some of your object key and it value will look like. It’s also used when creating a regular variables and angular reactive-forms when it comes to defining separate input validators. The meaning of the index signature is that within the square bracket ‘[key:string]’ represent a key name. And the ‘:any’ represent the return value of the key declared so, ‘[key: string]: any’ means our object property will have a key of string and can be assigned a value or a function that returns any. If you want type safety, it will be good to specify each key type if you already know what value will be assigned to it.

Note that the ‘name’ property is set to a type of ‘string’ in the ‘Student2’ object above. Typescript type checker will check the type of key, value that will be provided in position for the property if is of the same type. It will throw an error if invalid type value is assigned to it and also if you don’t provide the property because is not optional.

Check also, how to fix error – JSX expressions must have one parent element in React

Furthermore, you can specify different return value for a particular object key if you’re aware of the different kind of values it can take. Example, when declaring a variable to hold user’s mobile numbers, you may be confused of making the type string or number because both types will work. Therefore, you can make your life easy by declaring the variable of all two types so that a string or number can be assigned. There is something called type signature in all programming languages and that’s what is implemented in TypeScript to make variable types possible (research if you haven’t heard it). 

// Define the object type like below when you don't know ALL property names 
type Student2 = {
// Define a variable key (you can research how it work if you don’t have any idea)
// what do note is that the variable does not have a particular name.
  [key: string]: any | number; 
  name: string;
};

const obj2: Student2 = {
  name: 'James',
};
obj2.age = 30;

The above ‘[key: string]: any | number’ means that the object key can be indexed with a string key but it must be assigned a value or a function that returns string or number. The syntax of TypeScript union type is what we have used ‘string | number’ you can take your time and read about that from the official TypeScript documentation.

However, Typescript will throw “Error: Property 'id' of type 'number' is not assignable to 'string' index type 'string'.ts(2411)” if part of the object key is indexed with type and value of string and you declare another key of type number. You might think there is a bug with the type safety but I will recommend you learn something about union-type and index-signature first for clear understanding.

type Student2 = {
  [key: string]: string;
  name: string;
  // ⛔️ Error: Property 'id' of type 'number' is
  // not assignable to 'string' index type 'string'.ts(2411)
  id: number;
};

Check also, How to solve git error: failed to to push some ref to remote origin

Summary: Property does not exist on type Object

To fix the error “Property does not exist on type ‘{}’” in Typescript and when working with node, remember to access only object keys that exist. If there is a particular key that does not exist in your object, you have to explicitly add it to avoid this error. Take your time and read the above guide and get the whole concept right so that you will know how to deal with this type of bug whenever you’re presented with one.

Thanks for reading and if you have any suggestions or challenges applying above guide, let me know.

Tagged property does not exist on type

The property does not exist on type JavaScript error affects your program when you try to access or set a property that does not exist in the object’s type. Unfortunately, the property does not exist on type Angular affects most operating systems and programs, so predicting it is challenging, especially with complex applications.Property Does Not Exist on Type

Considering the need, we created this comprehensive debugging guide that will help you remove the type object mistake without affecting other processes, elements, and operations. In addition, we will help you recreate the property does not exist on type undefined error using typical code snippets and procedures, so continue reading for more information.

Contents

  • Why Is the Property Does Not Exist on Type Error Happening?
    • – Using JQuery in Visual Studio 2013
    • – Adding Return Type of Getters
    • – Applying Custom Formatting in TS
  • How To Fix the Property That Does Not Exist on Type?
    • – Add a Type With a Variable Key Name
    • – Adding Inputs in the Window Object
  • Conclusion

Why Is the Property Does Not Exist on Type Error Happening?

The property does not exist on type any typescript error happens when you try to access or set a property in your program that does not exist in the object’s class. In addition, the same error appears when you access a specific field without an array notation.

For instance, the property does not exist on type class error affects the elements that lack the right property, which can ruin other commands. Namely, a broken parent command usually obliterates the child elements due to the lack of fair properties, especially in complex applications and documents.

Considering that, we suggest changing the default property value to debug the program and remove the property does not exist on type component error. However, this is easier said than done because applying the debugging methods requires learning more about the bug’s core.

We will help you recreate the entire code exception that launches the property does not exist on type’ object error and affects secondary processes in your program. For a better understanding and a good grip on the topic, we will recreate the invalid script using standard elements and properties to elaborate on the error’s cause.

Still, the property does not exist on type but it does destroy other tags, so isolating the broken code snippet is practical and helpful. Then, we will discuss several debugging approaches that should reenable the commands in your document and launch all operations.

– Using JQuery in Visual Studio 2013

This article’s primary broken invalid instance uses several advanced operations in Visual Studio 2013 that launch the error and cause further complications. For example, the following script implements JQuery, JSRender, and JQuery UI with the latest patches and correct references. Unfortunately, although the system does not display errors in JavaScript, it blocks Visual Studio and prevents you from completing the processes.

You can learn more about the complete syntax below:

/// <reference path=”../ scripts/ typings/ jquery/ jquery.d.ts” />

/// <reference path=”../scripts/ typings/ jqueryui/ jqueryui.d.ts” />

/// <reference path=”typings/ jsrender/ jsrender.d.ts” />

var SUCSS = {};

$(document) .ready (function () {

SUCSS.fadeDiv();

});

SUCSS.fadeDiv = function () {

var mFadeText: number;

$(function () {

var mFade = “FadeText”;

//This part retrieves the info for the fadediv

$ .ajax({

type: “POST”,

//url: “/js/ General.aspx/ _FadeDiv1”,

url: “/js/ sucss/ General.aspx/ _FadeDivList”,

//data: “{‘iInput’:” + JSON.stringify(jInput) + “}”,

contentType: “application/ json; charset = utf-8”,

dataType: “json”,

error: function (status, error) {

// Show the error

//alert (xhr.Text);

},

success: function (msg) {

FadeText = msg.Fade;

// Replace the div’s content with the page principle’s return.

if (msg.d.FadeType == 0) {//FadeDivType = List

var template = $.templates(“#theTmpl”);

var htmlOutput = template.render(msg.d);

$(“[id$=lblFadeDiv]”) .html (htmlOutput);

}

else {//FadeDivType = String

$(“[id$=lblFadeDiv]”) .html (msg.d.FadeDivString);

}

},

complete: function () {

if (mFadeText == 0) {

$(“[id$=lblFadeDiv]”) .fadeIn (‘slow’) .delay (5000) .fadeOut (‘slow’);

}

}

});

});

As you can see, this script includes advanced processes that fail unexpectedly. Still, this is one of the few instances that force your system to display the incorrect exception.

– Adding Return Type of Getters

We experienced an identical inconvenience when adding return types of getters with straightforward processes. Therefore, we will show you a short code snippet that introduces the modules, exports the constants, and enables the return property for the getters.Property Does Not Exist on Type Causes

Later, we will demonstrate how to declare the modules’ return type, which, unfortunately, is broken. Finally, you can compare the processes to your document to pinpoint the failed operations that launched this mistake in the application.

The following example adds the return type of the getters:

type Module = {}

const MODULES: Module[] = [{}]

export const useUserStore = defineStore (‘user’, {

state: () => {

return {}

},

getters: {

check() {

return (module: Module) => true

},

modules() {

// this.check would get a TS2554: Expected 0 arguments, but got 1.

return MODULES.filter ((module) => this.check (module))

}

}

}

Although we can add other secondary processes and elements, we kept the script short to help you understand the error’s cause. So, this script confirms the property does not exist in the object’s type. We will now declare the return type for the modules to finish reproducing the error.

You can learn more about this instance in the following example:

export const useUserStore = defineStore (‘user’, {

state: () => {

return {}

},

getters: {

check() {

return (module: Module) => true

},

// Add return type

modules(): Module[] {

return MODULES.filter ((module) => this.check (module))

}

}

}

Although only a few code differences exist, both scripts are unfunctional and provoke your system to display the bug.

– Applying Custom Formatting in TS

This guide’s last broken script attempts to apply custom formatting in TS, which causes unexpected errors just like the one we are discussing now. Namely, this process launches the mistake when changing the environment variables and using the custom formatting, which is relatively easy in practice.

The following example provides the entire relevant code snippet:

declare module “slate” {

interface CustomTypes {

Editor: BaseEditor & ReactEditor;

Element: CustomElement;

Text: CustomText;

}

}

type CustomText = { text: string };

type CustomElement =

| { type: “paragraph”; children: CustomText[] }

| { type: “code”; children: CustomText[] };

const RichEditor = (): ReactElement => {

const editorRef = useRef<Editor>();

if (!editorRef.current) {

editorRef.current = withReact(withHistory(createEditor()));

}

const editor = editorRef.current;

const initialValue: Descendant[] = [

{

type: “paragraph”,

children: [{ text: “A line of text in the paragraph.” }],

},

];

const [value, setValue] = useState<Descendant[]>(initialValue);

const customRenderer = useCallback((props) => {

if (props.element.type === “paragraph”) {

return <Text {…props} />;

} else if (props.element.type === “code”) {

return <Code {…props} />;

}

}, []);

const formatCodeBlock = () => {

const [match] = Editor.nodes(editor, {

match: (n: Node) => {

console.log(n);

return n.type === “code”;

},

});

return (

<Box>

<Heading>Editor</Heading>

<Box p={2} border=”1px solid” borderColor=”slate.100″ rounded=”md”>

<Box py={2}>

<IconButton

icon={<RiCodeLine />}

onClick={formatCodeBlock}

aria-label=”sold”

size=”sm”

/>

</Box>

<Divider />

<Slate

editor={editor}

value={value}

onChange={(newValue) => setValue(newValue)}

>

<Editable renderElement={customRenderer} />

</Slate>

</Box>

</Box>

);

};

export default RichEditor;

This operation fails to render and apply the custom formatting, which halts your project. Luckily, this process requires a few code lines to debug the program without further complications.

How To Fix the Property That Does Not Exist on Type?

You can fix the property that does not exist on type by explicitly introducing the object property or using a variable of the same type. In addition, you can bypass or skip the Type Script type that checks whenever preferable because it is irrelevant when compiling your project or application.



So, we will first give you the immediate solution that introduces the correct object property. You can read the following example to learn about the broken code:

const object1 = {};

// accessing property not defined in the above object will throw an error

// Error: Property the ‘name’ does not exist on type ‘{}’.ts (2339)

object1.name = ‘Justice’;

The object in this example is JSON data your system receives as a response to the HTTP request made when running the application. You can quickly define the object explicitly if you know the required properties.

The following example provides the solution:

// Explicitly define the object type when you know all required property names

type Student = {

id?: number;

name?: string;

};

const obj: Student = {};

obj.id = 1;

obj.name = ‘John Doe’;

// Define the object type like below when you don’t know ALL property names

type Student2 = {

// Define a variable key (you can research how it work if you don’t have any idea)

// what do note is that the variable does not have a particular name.

[key: string]: any;

name: string;

};

const obj2: Student2 = {

name: ‘James’,

};

obj2.program = “TypeScript”;

This snippet completes the debugging approach, but fortunately, other processes exist.

– Add a Type With a Variable Key Name

This approach teaches you how to add a type with a variable key name to remove the mistake and allow all processes. As a result, we will provide two code snippets that complete the process, although knowing the names of all objects is not mandatory.Property Does Not Exist on Type Fixes

Therefore, the program will not launch the error when you access the element’s properties and values. In addition, we will show you the index signature that uses the critical string to establish the processes and inputs.

The following example provides the first step:

type Employee2 = {

[key: string]: any; // This is the variable key

name: string;

};

const obj2: Employee2 = {

name: ‘James’,

};

obj2.salary = 100;

So, the script will return any type value when the object is indexed with a string key, which is beneficial and does not block your code.

On the flip side, you can avoid this error if you know the names of all objects’ keys and the shape of values. Therefore, you can implement more specific index signatures for improved safety and recognition.

We suggest applying the principle from the following code snippet:

type Employee2 = {

[key: string]: string | number;

name: string;

id: number;

};

const obj2: Employee2 = {

id: 1,

name: ‘James’,

};

obj2.department = ‘accounting’;

obj2.salary = 100;

So, unlike the previous instance, the object key indexed with a string key from this snippet will return a number or string type. However, remember to apply this approach to all invalid elements in your document.

– Adding Inputs in the Window Object

You can quickly get around this code exception by adding inputs in the window object and the corresponding interface. The following code script shows how you can do it:

declare global {

interface Window { // notice that “Window” is capitalized here

hello: any;

}

}

export const addWindowStuff = () => {

window.hello = () => console.log(“hello world”);

};

Luckily, you can improve your code by moving the global declaration to the index file. In addition, we suggest opening an appropriate type for the global variable, as shown here:

// types/index.ts

export {};

declare global {

interface Window {

hello: () => void;

}

}

This simple code alteration boosts your script’s performance and prevents further mistakes.

Conclusion

The property JavaScript error affects your program when you try to access or set a property that does not exist in the object’s type. So, let us summarize the critical points from this guide before you leave:

  • Accessing the only object keys that exist should debug your program or application
  • You must add a specific key in the object if it does not exist to avoid the error
  • The scripts that recreate the error should help you pinpoint the invalid elements
  • Remember to apply the solutions to all incorrect properties and elements inside your document

Any debugging process or approach can be complicated if you miss a single step, especially with complex projects. Luckily, this guide used simple techniques to provide quick solutions for this annoying mistake.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Cover image for How to fix 'Property does not exist on type Window in TypeScript' error

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Rob Kendal {{☕}}

Blog header image for how to fix property does not exist on Window article

If you’ve been doing something with an external library, global variable or anything that involved the native Window object in TypeScript, you may have come across this error:

Property does not exist on type ‘Window & typeof globalThis’.ts (123)

It’s a pain, but really simple to fix, so let’s get to it!

Discovering the ‘Property does not exist on type Window in TypeScript’ error

I was recently working on a client site and it involved using the excellent Cloudinary service. They have some equally excellent embeddable widgets which only require a bit of simple JS to drop in. Here’s a snippet of the code:

const myWidget = window.cloudinary.createUploadWidget(options, processResults);
// ...rest of the file

Enter fullscreen mode

Exit fullscreen mode

The problem is, this was a React app in Next.js and a TypeScript codebase at that! The code worked fine, but the classic ‘Property does not exist on type Window in TypeScript’ error flagged up on the build command and TypeScript complained about it endlessly.

Identifying the problem

The Window type is defined in the lib.dom TypeScript module (as per the following documentation on TSDoc. You can see we have the global Window object definition here with a ton of properties.

If you need anything not defined in this list, however, then that’s when you’ll hit the Property does not exist on type 'window & typeof globalthis'.ts style error. Common examples of this are when you add external libraries from Google for their analytics or Tag Manager, or, in my case, Cloudinary.

Cloudinary added it’s own cloudinary object to the global window object provided by the browser, but TypeScript has no idea what it is or what types it has because they’re not defined.

This is one of those cases where the error is actually pointing us in the right direction.

twitter banner call to action

Fixing the ‘Property does not exist on type Window in TypeScript’ error

Fortunately for us, the fix is quite simple and involves three steps:

  1. Creating an index.d.ts file somewhere in our project.
  2. Editing the file to define the types on the Window object.
  3. (optional) adding a reference to the file in the tsconfig.json file.

Starting with number 1, you’ll need to add the following into your index.d.ts file:

export {};

declare global {
  interface Window {
    somePropertyHere: any;
  }
}

Enter fullscreen mode

Exit fullscreen mode

If you don’t have such a file, then create a folder in your project root or src folder called types. In here, add a new file called index.d.ts and then add the previous code snippet in there.

If you already have an index.d.ts file or a global.d.ts (or any other declared project types file) in your project with other type definitions in it, then you may not need the export {} line. You can omit that part and add the rest.

You can define whatever other properties you’d like in here as per your project needs, e.g.

export {};

declare global {
  interface Window {
    cloudinary: any;
    gtag: (...args: any[]) => void;
  }
}

Enter fullscreen mode

Exit fullscreen mode

In the above snippet, you’ll see I added the cloudinary global object with a type of any as, unfortunately Cloudinary don’t seem to offer a TypeScript option for their widgets so we’re unsure what the cloudinary object will contain. However, with the gtag one, we know that it is a function that has a void return type.

Where possible, always try to strongly type your properties if you can, rather than opting for any.

Finally, if you’re still experiencing issues, you might need to do one last step to wire things up. Take a note of your index.d.ts file’s location and head into your tsconfig.json file, which should be in the root of your project:

{
  "compilerOptions": {
    // ... other settings
    "typeRoots": ["./src/types", "./types"]
  }
}

Enter fullscreen mode

Exit fullscreen mode

Under the typeRoots property (an array), make sure you have a path to the containing folder for your index.d.ts file. In my case it was in ./src/types so I added that in my tsconfig.json file.

Wrapping up

And it’s a simple as that. If you’ve been plagued by TypeScript’s complaints about a ‘Property does not exist on type Window in TypeScript’ error, you should have the knowledge and really simple steps to fix that once and for all.

Today’s topic, I will show you how to solve the ‘property does not exist on type object‘ error in Typescript. But before that, let’s find out what causes it. Stay tuned to better understand the solutions.

Why does the “Property does not exist on type Object” error in TypeScript happen?

This error happens when you work with TypeScript, a frontend application has accessed the global window object. This might occur when you are adding something to this global object. 

Example: 

let student: object;
student = {
  name:  "Johnny Kaiz",
  id: 123,
  age: 18
};

console.log(student.tuitionfee);

Output: 

error TS2339: Property 'tuitionfee' does not exist on type 'object'

When you try to access a property like: console.log(student.tuitionfee) the program will crash because the property ‘tuitionfee‘ is does not exist in ‘student’ object.

How to fix this error?

Adding property to the type we set to the variable

If you already know the property’s name and value, just add it variable. To specify the object’s properties, you should declare the following syntax.

Example:

let student: object;
student = {
  name: string,
  id: number,
  age: number,
  tuitionfee: number
};

Then you assign data type to each variable in ‘student’ object :

student = {
  name: "Johnny Kaiz",
  id: 123,
  age: 18,
  tuitionfee: 10000
};

Output:

{
  "name": "Johnny Kaiz",
  "id": 123,
  "age": 18,
  "tuitionfee": 10000
}

Using Object.assign() feature

You don’t want to worry about types and don’t use TypeScript. 

You can use  Object.assign() feature. 

Object.assign() is used to copy the values ​​of all properties of one or more source objects to a target object.

Syntax:

Object.assign(target, sources)

Parameters:

  • target: Target object
  • sources: Source objects 

Example:

const sourceObj = {tuitionfee : 10000};

let student: object;
student = {
  name: "Johnny Kaiz",
  id: 123,
  age: 18
};

const newStudent = Object.assign(student, sourceObj);
console.log(newStudent); 

Output :

 { 
    name: 'Johnny Kaiz',
    id: 123,
    age: 18,
    tuitionfee: 10000
 }

Using KEYABLE 

This method is ​​used when you don’t know the object’s name or data.

Syntax:

 {[key: string]: any}

The value of this syntax returns is ‘any’ type.

Example:

let student: object;
student = {
  {[key: string]: string};
  name: string;
};

Summary 

The above methods solve the “Property does not exist on type Object” error in Typescript. If you have any questions or helpful solutions, just feel free to leave them in the comment below, and don’t forget to wait for our new articles in LearnShareIt. 

Maybe you are interested:

  • “Tsc Command Not Found” in TypeScript
  • How To Solve The Error: Object Literal May Only Specify Known Properties In TS
  • Cannot invoke an object which is possibly ‘undefined’ in TS

Jason Wilson

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.


Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

How to Fix «Property ‘…’ does not exist on type ‘EventTarget'» TypeScript Error?

  • 24 Oct, 2020

  • 6 min read

Let’s suppose we have the following HTML element:

<div id="foo"></div>

With the following code snippet we will receive the element above as an event target in our event listener:

const elem = document.getElementById('foo');

elem.addEventListener('test', function (e) {
    // Property 'id' does not exist on type 'EventTarget'.
    console.log(e.target.id); // 'foo'
}, false);

elem.dispatchEvent(new Event('test'));

This code runs perfectly fine because we know we’re expecting the event target to be an HTML element, and we are certain that the HTML element has the property id. However, TypeScript complains about the id property not existing on the EventTarget type. This is because:

  • By default an event target element has an EventTarget type in TypeScript;
  • The EventTarget type does not inherit from the Element type which is why TypeScript fails to recognize properties such as id, class, etc. that we would expect to exist on a typical Element object.

Why Does the EventTarget Type Not Inherit From Element Type?

The reason this is the case is simply because all event targets might not be HTML elements. For example the event target can be also be XMLHttpRequest, FileReader, AudioNode, AudioContext, etc.

How to Fix This Error?

To make TypeScript understand the correct type for the event target, we can specify it like so:

const elem = document.getElementById('foo');

elem.addEventListener('test', function (e) {
    const target = e.target as Element;
    console.log(target.id); // 'foo'
}, false);

elem.dispatchEvent(new Event('test'));

We can also inline it like so:

(e.target as Element).id

Alternatively, we can also do the following if we only need to use the target property from the event:

const elem = document.getElementById('foo');

elem.addEventListener('test', function (e: { target: Element }) {
    console.log(e.target.id); // 'foo'

    // Property 'type' does not exist on type '{ target: HTMLInputElement; }'.
    console.log(e.type);
}, false);

elem.dispatchEvent(new Event('test'));

As it is evident from the example above, after specifying the correct type for e.target it works fine. However, other properties (such as e.type, etc.) would throw a TypeScript error. If we need to access those other properties of the event as well, we could do so in the following way:

const elem = document.getElementById('foo');

elem.addEventListener('test', function (e: Event & { target: Element }) {
    console.log(e.target.id); // 'foo'

    // other Event object properties are recognized too now:
    console.log(e.type); // 'test'
}, false);

elem.dispatchEvent(new Event('test'));

We can, of course, get more specific with the type of the target events. For example, let’s suppose we wanted to get the value attribute of the following target input element:

<input id="foo" type="text" value="bar" />

Without setting the proper type for the event target, we’ll get the «Property 'value' does not exist on type 'EventTarget'» error while trying to get the value property of the input element. Therefore, as discussed earlier, we need to assert the type we expect the event target to be like in the following way for example:

const elem = document.getElementById('foo');

elem.addEventListener('test', function (e) {
    console.log((e.target as HTMLInputElement).value); // 'bar'
}, false);

elem.dispatchEvent(new Event('test'));

In the code above we used a more specific type (i.e. HTMLInputElement) because the value property does not exist on the generic Element type. The HTMLInputElement type inherits from the Element type though. Therefore, it will have the generic element properties (such as id, class, etc.) as well as the more specific ones that exclusively exist on the HTMLInputElement object (such as value, validity, etc.).

Common Errors

Let’s see a few more examples of some common errors associated with this issue:

Property ‘files’ does not exist on type ‘EventTarget’:

Assuming that the event target is <input type="file">, we can fix this error like so:

// Property 'files' does not exist on type 'EventTarget'.
e.target.files;

// possible fix:
(e.target as HTMLInputElement).files;

Property ‘controls’ does not exist on type ‘EventTarget’:

Assuming that the event target is an HTML audio/video element, we can fix this error like so:

// Property 'controls' does not exist on type 'EventTarget'.
e.target.controls;

// possible fixes:
(e.target as HTMLMediaElement).controls;
(e.target as HTMLVideoElement).controls;
(e.target as HTMLAudioElement).controls;

Here, using the HTMLMediaElement should be sufficient. However, we can also do the following when the target element can be either an audio or a video element:

type MediaType = HTMLVideoElement | HTMLAudioElement;
(e.target as MediaType).form;

Property ‘form’ does not exist on type ‘EventTarget’:

Assuming that the event target is an HTML input element, we can fix this error like so:

// Property 'form' does not exist on type 'EventTarget'.
e.target.form;

// possible fix:
(e.target as HTMLInputElement).form;

Assuming that the event target is an HTML textarea element, we can fix this error like so:

// Property 'form' does not exist on type 'EventTarget'.
e.target.form;

// possible fix:
(e.target as HTMLTextAreaElement).form;

If the target element can be either an input or a textarea element, we can create a new intersection type like so:

// Property 'form' does not exist on type 'EventTarget'.
e.target.form;

// possible fix:
type InputType = HTMLInputElement | HTMLTextAreaElement;
(e.target as InputType).form;

Property ‘checked’ does not exist on type ‘EventTarget’:

Assuming that the event target is an HTML <input type="radio"> or <input type="checkbox"> element, we can fix this error like so:

// Property 'checked' does not exist on type 'EventTarget'.
e.target.checked;

// possible fix:
(e.target as HTMLInputElement).checked;

Property ‘src’ does not exist on type ‘EventTarget’:

Assuming that the event target is an HTML <img> element, we can fix this error like so:

// Property 'src' does not exist on type 'EventTarget'.
e.target.src;

// possible fix:
(e.target as HTMLImageElement).src;

Assuming that the event target is an HTML <source> element, we can fix this error like so:

// Property 'src' does not exist on type 'EventTarget'.
e.target.src;

// possible fix:
(e.target as HTMLSourceElement).src;

Property ‘classList’ does not exist on type ‘EventTarget’:

The classList property exists on every HTML element, so we could use Element, HTMLElement or a more specific type (for e.g. HTMLInputElement, etc.). For example:

// Property 'classList' does not exist on type 'EventTarget'.
e.target.classList;

// possible fixes:
(e.target as Element).classList;
(e.target as HTMLElement).classList;
// etc.

Property ‘parentNode’ does not exist on type ‘EventTarget’:

The parentNode property exists on every HTML element, so we could use Element, HTMLElement or a more specific type (for e.g. HTMLInputElement, etc.). For example:

// Property 'parentNode' does not exist on type 'EventTarget'.
e.target.parentNode;

// possible fixes:
(e.target as Element).parentNode;
(e.target as HTMLElement).parentNode;
// etc.

Hope you found this post useful. It was published 24 Oct, 2020. Please show your love and support by sharing this post.

Понравилась статья? Поделить с друзьями:
  • Project zomboid ошибки с модами
  • Project zomboid ошибки в правом нижнем углу
  • Project zomboid ошибка что делать
  • Project zomboid ошибка при создании сервера normal termination
  • Project zomboid ошибка при создании мира