Tips for effectively utilizing the 'or' operator when working with disparate data types

One of my functions requires an argument that can have one of two different types.

If you're interested in TypeScript functions and types, take a look at the official documentation, as well as these Stack Overflow questions: Question 1 and Question 2.

This is the function:

  public onKeydown(ev: KeyboardEvent | EventTarget): void {
    if (ev.keyCode === 13) {
      this.sendMessage();
      ev.target.blur();
    } else {
      this.chatService.emitTyping();
    }
    return;
  }

This is the HTML for the page:

          <textarea
            autosize
            [minRows]="1"
            [maxRows]="4"
            [(ngModel)]="message"
            placeholder="Type your message here"
            class="msg-input"
            (keydown)="onKeydown($event)"
            (click)="scrollToBottom()"
          ></textarea>

I'm struggling to incorporate the two different types within the onKeyDown function properly. It seems that the use of '|' does not behave in Angular as it should according to the TypeScript documentation. For instance, when the 'Enter' key is pressed, I want to blur the keyboard and send the message. Do I need to create a separate function just to blur the keyboard?

The error message I'm encountering reads:

ERROR in src/Components/chat/chat.component.ts(72,12): error TS2339: Property 'keyCode' does not exist on type 'EventTarget | KeyboardEvent'.

[ng] Property 'keyCode' does not exist on type 'EventTarget'.

[ng] src/Components/chat/chat.component.ts(74,10): error TS2339: Property 'target' does not exist on type 'EventTarget | KeyboardEvent'.

[ng] Property 'target' does not exist on type 'EventTarget'.

Answer №1

It seems that typescript is getting confused because the action you are trying to perform is not compatible with both EventTarget and KeyboardEvent. You need to specify directly which type it is in the function. For example:

public onKeydown(ev: KeyboardEvent | EventTarget): void {
    if (<KeyboardEvent>ev.keyCode === 13) { // updated line
      this.sendMessage();
      ev.target.blur();
    } else {
      this.chatService.emitTyping();
    }
    return;
}

You could also try:

if ((ev as KeyboardEvent).keyCode === 13) {

Keep in mind that sometimes Angular might still have trouble finding the property you're looking for, even if it exists in the DOM object. In that case, you can combine types like:

type KeyboardCustom = KeyboardEvent & { customProp?: string };

This means that it satisfies both interfaces simultaneously (with the second one being optional, so no errors will be thrown if it's missing). You can take it a step further with Partials.

type CustomInterface = KeyboardEvent & Partial<KeyboardInterface>

where KeyboardInterface has some defined structure.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Socket.io Client: Consistently receiving error messages for an incorrect

Here is the server-side code: import http from 'http'; import Koa from 'koa'; import { Server } from 'socket.io'; (async () => { const app = new Koa(); var server = http.createServer(app.callback()); var io = new Se ...

The 'Set-Cookie' response header failed to be recognized for a subsequent HTTP request

When a user successfully logs in, their information is stored in a cookie using the "Set-Cookie" response header. However, I am facing an issue where the cookie seems to get lost when making subsequent requests from the client. As a result, the server trea ...

Clearing the require cache in Node.js using TypeScript

I need to repeatedly require a module in TypeScript and Node for testing purposes. I came across an approach on this post which suggests the following code snippet: const config = require('./foo'); delete require.cache[require.resolve('./fo ...

Providing Access to Data Across Various Modules

I currently have an application structured like this: AppModule SubModule Multiple Components SecondSubModule Multiple Components I am looking to perform a data call to a REST API that will be used by both SubModule and SecondSubM ...

What strategies can I use to address the issue of requiring a type before it has been defined?

Encountered an intriguing challenge. Here are the types I'm working with: export interface QuestionPrimative { question : string; id : string; name : string; formctrl? : string; formgrp? : string; lowEx ...

What are the steps for deploying an Angular 2 project to a server with PUTTY?

After developing an Angular 2 app with Angular-CLI on my local server, I have reached the production phase and now need to upload it to a CentOS server using Putty. I attempted to follow instructions from this source for installing node and npm on the ser ...

Deactivate multiple textareas within a loop by utilizing JQuery/Typescript and KnockoutJS

I am working on a for loop that generates a series of textareas with unique ids using KO data-binding, but they all share the same name. My goal is to utilize Jquery to determine if all the textareas in the list are empty. If they are, I want to disable al ...

Preventing duplicate actions on a Subject with Angular 7's rxjs debounceTime operator

While working on an Angular7 application, I encountered an issue where the KeyUp event of a numeric input was being captured by this specific HTML code: <input fxFlex type="number" formControlName="DM" (keyup)="changeDM()"> </div& ...

Encountering problem when creating new app with Angular CLI version 6.0.4 and specifying the

I just used npm to globally install angular cli version 6.0.4 with the command `npm install -g @angular/cli`. However, when I attempt to create a new project using `ng new my-first-app`, an error message is displayed: The input for the schematic does not ...

Limit the types of components allowed as children in a React component by utilizing TypeScript

I've been struggling with this question for a while, searching through answers but still unable to get my code to work. Here's the issue at hand. Within my code, I have a component called Steps which acts as a wrapper. I also have multiple Step ...

What is the best RxJS operator to implement additional transformations following mapping?

this.service.retrieveObject(id).map((object)=>{ return transformation1(object); }) .map((object)=>{ return transformation2(object); }); In the following example, the second map call does not have access to the object ...

Graphql is a revolutionary method for structuring entities in a hierarchical schema

Hey there! I'm fairly new to the world of GraphQL, and I've been curious about whether it's possible to organize entities into a tree schema similar to how Swagger handles it. I'm using Apollo Server for my UI/debugging of my GraphQL. ...

What is the best way to encapsulate a class with generic type methods within a class that also has a generic type, but without any generic type arguments on its methods?

Below is an example of the code I am working with: class Stupid { private cache: Map<any, any> = new Map(); get<T>(key: string): T { return this.cache.get(key); }; } class Smart<T> extends Stupid { get(key: string): T { s ...

Utilizing Global Variables and Passing Values in Ionic 3

It seems like my issue is rather straightforward, but there is definitely something eluding me. After logging in, I need to store a TOKEN for HTTP requests in a global variable. Upon successful login, the HTTP get method returns an object with the HTTP co ...

What is the best way to make mouse and touch events trigger responses in Angular versions 9 and above?

I've been searching high and low for a library or tried-and-true method to handle common user events reactively, but unfortunately my quest has come up empty. After some digging, I stumbled upon what seemed like a solid solution: https://github.com/t ...

I'm unable to resolve all parameters for xxx -- unit testing using jest

I recently encountered an issue with a test in jest that is failing and displaying the following error message: Error: Can't resolve all parameters for LoginService: (?). at syntaxError (/Users/wilson.gonzalez/Desktop/proyecto_andes/external/npm/nod ...

Is there a way to monitor user engagement within my app without depending on external analytics platforms?

I'm looking to enhance the user-friendliness of my applications deployed on the Play Store by tracking users' interactions. Specifically, I want to keep track of: Screen Time: Monitoring how much time users spend on each screen. Clicks: Tracking ...

Tips on how to integrate a Twitter timeline into an Angular 6 application

I've been trying to integrate a Twitter timeline into an Angular 6 application, but I have yet to find a satisfactory solution. Here's what I've attempted so far: Inserted the Twitter generated code from 'publish.twitter.com' int ...

Tips for importing a .geojson document in TypeScript using webpack?

I am trying to extract data from a .geojson file but faced some challenges while attempting two different methods: const geojson = require('../../assets/mygeojson.geojson'); The first method resulted in an error message stating: Module parse f ...

Why doesn't WebStorm display TypeScript inspection errors in real-time?

I'm currently utilizing WebStorm 2017.2.4 in conjunction with Angular 4.3 - I am facing an issue where TypeScript errors are not being displayed: Query How can I enable real-time inspections to occur immediately? (I've already attempted invali ...