Skip to content

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

Closed
@mxdvl

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') : [];

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions