Answer the question
In order to leave comments, you need to log in
How to correctly determine the type of an object in Typescript (React)?
I define the type as a rule for the received or my data using enums, type's, interfaces.
You can also get the type using an expression:
instance.constructor.name
But what if this does not work:
<button onClick={e => switchTheme(e)} …
// Выдаст ошибку о том что имя не найдено
const switchTheme = (e: SyntheticBaseEvent) => {
e.target.classList.remove(clickedClass);
interface ClickableProps {
children: JSX.Element[] | JSX.Element;
}
Answer the question
In order to leave comments, you need to log in
The typescript correctly swears because the event target does not have to be a home element. Events can also be generated, for example by XHR requests.
If I were you, I would make a so-called type guard function, in which I would make sure that the target is indeed a home element. All home elements inherit from the HTMLElement object. This can be used to check:
const isHtmlElement = (v: any): v is HTMLElement => v instanceof HTMLElement;
const eventHandler = (e: Event) => {
if (!isHtmlElement(e.target)) {
return;
}
// Вот здесь мы можем смело работать с таргетом как с ДОМ Элементом
e.target.classList.toggle('active');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question