Hey I am new to Typescript and I am having some trouble implementing Event Target.
What is the typescript equivalent for event.target.matches that is used in Javascript?
Example code:
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
Use a type assertion to type event. target in TypeScript, e.g. const target = event. target as HTMLInputElement . Once typed correctly, you can access any element-specific properties on the target variable.
To type the onChange event of an element in React, set its type to React. ChangeEvent<HTMLInputElement> . The ChangeEvent type has a target property which refers to the element. The element's value can be accessed on event.
The EventTarget interface is implemented by objects that can receive events and may have listeners for them. In other words, any target of events implements the three methods associated with this interface.
The error "Property 'value' does not exist on type 'EventTarget'" occurs when we try to access the value property on an element that has a type of EventTarget . To solve the error, use a type assertion to type the element correctly before accessing the property. This is the index.
You'd need to cast (type assertion) event.target
as something like a HTMLElement
to provide access to HTMLElement
methods such as matches()
. Without the cast, event.target
is typed as EventTarget
which is why you are not seeing matches()
or other HTMLElement
methods being available.
if (!(<HTMLElement> event.target).matches('.dropbtn')) { }
Here is an example in action.
window.onclick = function(event) {
if (!(<HTMLElement> event.target).matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
Per the suggestions from @WsCandy you could also use as
as an alternative:
window.onclick = function(event) {
const target = event.target as HTMLElement;
if (!target.matches('.dropbtn')) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With