A
A
Alexey2021-06-07 13:10:34
typescript
Alexey, 2021-06-07 13:10:34

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) => {


I change SyntheticBaseEvent to MouseEvent but in the line below it says "TS2339: Property 'classList' does not exist on type 'EventTarget'.":
e.target.classList.remove(clickedClass);

Or for example:
interface ClickableProps {
    children: JSX.Element[] | JSX.Element;
}


How to understand that children is of type JSX.Element..?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Demian Smith, 2021-06-07
@azovl

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;

then we can use this function to test our target:
const eventHandler = (e: Event) => {
  if (!isHtmlElement(e.target)) {
    return;
  }
  // Вот здесь мы можем смело работать с таргетом как с ДОМ Элементом
  e.target.classList.toggle('active');
}

UPD
More food for thought.
The final code generated by the typescript does not contain type information. In runtime, you cannot find out the interface type by doing, for example, `remennaya instanceof VashInterfeis`. But you can always create a type guard function that will determine that the object is of the right type by some indirect signs (for example, by the presence of certain fields in the object). Since the code of the guard function cannot be checked with a static analyzer, the typescript cannot guarantee that your guard function is correct and does not skip everything. Therefore, it is good practice to write code that does not need such checks. It's possible. With this approach, the code becomes slimmer and easier to understand.

A
Alice, 2021-06-07
@w3bsmes

Indeed, why ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question