Skip to content

How to check for undefined members of object on legacy browsers? #5853

Closed

Description

@mxdvl

As raised by @bryophyta in #5849 (comment), there are several ways of checking whether an method exists as a member of an object. We also have an auto-fixing ESLint rule that prevents us from using optional chaining on non-nullish values.

For example, the window.performance.getEntriesByType method is defined in lib.dom.d.ts, so we need to circumvent this rule to prevent errors in production.

Which options do people prefer?

// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- not all browsers have this method
const option1  = window.performance.getEntriesByType?.('measure') ?? [];

const option2  = 'getEntriesByType' in window.performance ? window.performance.getEntriesByType('measure') : [];

const option3  = typeof window.performance.getEntriesByType === 'function' in  ? window.performance.getEntriesByType('measure') : [];

Activity

  1. bryophyta commented on Aug 25, 2022

    @bryophyta
    Contributor

    Thanks for this! If option1 is functionally equivalent to the others then I'd be inclined towards that? It looks like the issue here is essentially in the type definitions themselves, right? (I'm assuming that TS is basing its definitions here on a set of browsers that it's decided to support?) So being explicit that this is the source of the issue here seems like a good idea to me. But I don't have a super strong opinion on this :)

  2. added this to the Health milestone on Oct 4, 2023
  3. locked and limited conversation to collaborators on Oct 11, 2023
  4. converted this issue into a discussion #9097 on Oct 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions