Class DatasetWrapper<DS, TN>

Wrapper for managing the dataset property on an element.

Trying to work with the dataset property using TypeScript is not great. You have to repeatedly perform a bunch of type checks, which is tedious and results in overly-verbose code. This class makes it much easier to get and set properties of the dataset (which map to the corresponding data-* attributes on an element).

The dataset property is a (very barebones) DOMStringMap. This wrapper class enables you to get and set values of any type that can be stringified while retaining type safety via the DS generic passed in.

See usage examples in wrapDataset.

Type Parameters

  • DS extends AnyDatasetShape

    The shape of the dataset data.

  • TN extends TagName = "*"

    Tag name of element with which the dataset is associated.

Constructors

Accessors

Methods

  • Gets the element attribute name (i.e. data-<key>) for the specified key.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K

      Dataset key for which to get attribute.

    Returns string

    Dataset attribute name associated with the specified key.

  • Returns the value of the dataset entry with matching key.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K

      Key of the dataset entry to get.

    Returns undefined | DS[K]

    Dataset property value associated with the specified key.

  • Builds an object with all defined dataset attribute values. Note that the return value is a Partial because the expected shape of the dataset specified in the DS generic doesn't necessarily correspond to dataset properties that exist on the element.

    Returns Partial<DS>

    Object with dataset entries that exist.

    HTML

    <div id="example" data-count="20">Example</div>
    

    Code

    const element = findElement("#example");

    const data = wrapDataset<{ count: number; label: string }>(element);

    // Note that `label` is missing because there is no `data-label` attribute
    // on the specified element:
    const entries = data.getAll();
    // { count: 20 }
  • Removes the dataset entry associated with the specified key.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K

      Key of the dataset entry to remove.

    Returns this

  • Sets the dataset entry with the specified key to the specified value.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K

      Key of the dataset entry to update.

    • value: DS[K]

      Value to set for the dataset entry.

    Returns this

  • Updates the element's dataset property values to match the entries object specified. You can pass in a subset of the shape of dataset and only those values will be updated.

    Parameters

    • entries: Partial<DS>

      Data to update in the dataset.

    Returns this