Ways to verify the presence of a DOM function in TypeScript prior to its utilization

How can I write the following code in TypeScript without getting an error from the compiler?

if(navigator.share)
{
    navigator.share(...);
}

The specific error message is: Property share is not found in navigator.

It's worth noting that Navigator.share is a function that some browsers have while others don't. Is there a way to adjust my TypeScript code so that the compiler doesn't throw an error, while still performing the necessary check?

Answer №1

If you want to implement it, follow these steps:

    if (navigator['share']) {
        const share = navigator['share'];
        share();
        console.log(navigator['share']);    
    }

@cyrix continues to argue that this code will result in a compiler error. It won't. Check out this screenshot showing the code in action

https://i.sstatic.net/nGKOa.png

Answer №2

There are various ways to determine if a property exists on an object:

1. To check if an object owns a property, you can use:

if(car.hasOwnProperty('model')) {
  // ...
}

2. If you want to confirm if a property is part of the object's prototype, you can utilize:

if(Object.getPrototypeOf(car).hasOwnProperty('model')) {
  // ...
}

Note: car.__proto__.hasOwnProperty could also work, but it's only consistent since the ECMAScript2015 spec.


3. To verify if a property exists on an object, you can use:

if(car['model']) {
  // ...
}

You should also ensure to check its type as typeof Function before invoking it.


In your particular case, if model is part of the Car.prototype, the second option would be suitable. Additionally, you need to inform TypeScript that the car has the model method because car['model']() will fail if the noImplicitAny option is enabled.

if (Object.getPrototypeOf(car).hasOwnProperty('model')) {
  if(typeof (car as Car & { model: Function }).model === typeof Function) {
    (car as Car & { model: Function }).model()
  }
}

For the TypeScript compiler, the

(car as Car & { model: Function }).model()
section is crucial.

Alternatively, you could define your own global type for the experimental Car.model method:

type ExperimentalCarModel = (details:
        { brand: string, year?: number, color?: string }
        | { brand?: string, year: number, color?: string }
        | { brand?: string, year?: number, color: string }
) => void;

declare type ExperimentalCar = Car & {
    model: ExperimentalCarModel
}

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

The condition in a Typescript function that checks for strings will never evaluate to true

I encountered a strange issue with a TypeScript condition in a function. Here is my current code, where the parameters are passed from outside: getLevel(validation: string, status: string): string { let card = ""; if (validation == &qu ...

Unexpectedly, the current value is not displayed in the Angular2 dropdown select element that contains multiple group options

Within my Angular2 application, I have a dropdown element with 3 different option groups. Here is how it's structured: <select formControlName="reasonCode" id="reasonCode" class="form-control"> <option value="" [ngValue]="null">< ...

Assigning a dynamic name to an object in Typescript is a powerful feature

Is there a way to dynamically name my object? I want the "cid" value inside Obj1 to be updated whenever a new value is assigned. I defined it outside Obj1 and then called it inside, but when I hover over "var cid," it says it's declared but never used ...

Successfully initializing FormArray values using patchValue method

In my application, I have a table of cashflows where each cashFlow consists of a varying number of periods. When a cashflow is clicked, I am attempting to populate a component so that the period values can be edited. The cashflow name along with the start ...

Tips for sidestepping nested TypeScript if statements by declaring a variable like so: `let x: type | undefined =

Is there a more efficient approach to handling type checking for variables defined as type | type2? For instance, consider the following code snippet: if (e) { let targetElement: Element | undefined = e.toElement; if (targetElement) { ...

JavaScript now has Type Inference assistance

When attempting to utilize the Compiler API for processing JavaScript code and implementing Type inference to predict types of 'object' in a 'object.property' PropertyAccessExpression node, I encountered some issues. Some simple example ...

Ways to access a property within an object using TypeScript

Can you help me extract the "attributes" array from this object and store it in a new variable? obj = { "_id": "5bf7e1be80c05307d06423c2", "agentId": "awais", "attributes": [ // that array. { "created ...

Listen for browser dismissal at the Expo

In my app created with expo react native, I have a scenario where the user is navigated to a URL using a WebBrowser. Is there a way for me to detect when the user closes or dismisses this WebBrowser and trigger a specific function accordingly? ...

What is the reason for this JSON attribute showing up as undefined in the logs?

Recently, I've set up a nodejs lambda function that is triggered by an SQS queue connected to an SNS topic. Here's a snippet of the lambda code: 'use strict'; import { Handler } from 'aws-lambda'; const myLambda: Handler = ...

Angular 2.4.8's need for Node.js dependency

I recently started working with angular 2.4.8 and have been exploring tutorials on the angular website. However, I've noticed that all angular libraries are typically imported using node modules (via package.json for installing Node.js). Is it mandato ...

Displaying inner arrays in an Angular2 MatTable

Welcome to my initial post on Stack Overflow, where I hope to communicate my query clearly. I am currently attempting to develop a table with dynamic columns. However, I am encountering difficulty in comprehending how to bind matColumnDef to a specific el ...

Combining two sets of JSON arrays

Looking to combine two arrays based on the same id, merging them into one array. Example: { "id":1212, "instructor":"william", ... } Array 1: [ { "id":1212, "name":"accounting", ... }, { ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Create a series of actions that do not depend on using only one occurrence of the WriteBatch class

My goal is to create a series of batch actions using functions that do not require a specific instance of WriteBatch. Currently, I am passing an instance of the WriteBatch class to the functions so they can utilize the .set(), .update(), or .delete() metho ...

Discovering the general function types in TypeScript

Currently, I am in the process of developing a function to generate Redux actions (similar to createAction from redux toolkit). My goal is to create a function that can produce action generators based on the types provided to the creator function. const c ...

Icon that can be clicked in a div container

Is there a way to prevent the div click event from being triggered when clicking on ion-icon? <div(click)="goNext()"> <ion-icon name="close-circle-outline" size="large" (click)="dissmiss()"></io ...

Utilize the type name as the indexer for the interface

Issue with Abstract Concepts My challenge involves relating two distinct groups of types to one another. // Group A interface Hello { ... } interface Foo { ... } // Group B interface World { ... } interface Bar { ... } To tackle this problem, I am crea ...

Tips on triggering the subscribe function only when either the parameter or one key-value pair of the query parameter changes

In my current situation, I need to trigger the subscribe action only when either the parameters in the URL change or when showList changes in the query parameter. The rest of the query parameters like page=0&size=5&sort=name,asc are added for scena ...

What causes Typescript to accept some objects and reject others?

I find the behavior of the Typescript compiler quite perplexing in relation to this code. I am using JSON.parse to populate a class instance from another class instance's output of stringify. It seems like the return value of JSON.parse is simply a r ...

Ending the connection in SignalR upon $destroy

I am currently working on a page that is utilizing SignalR, Angular, and Typescript. Upon the destruction of the current $scope (such as during a page change), I make an attempt to disconnect the client from the SignalR server: Controller.ts $scope.$on(&q ...