[Typescript] DOMNodeExtractorConfig

import { it } from 'vitest';
import { Equal, Expect } from '../helpers/type-utils';

export const isDivElement = (element: unknown): element is HTMLDivElement => {
  return element instanceof HTMLDivElement;
};

export const isBodyElement = (element: unknown): element is HTMLBodyElement => {
  return element instanceof HTMLBodyElement;
};

interface DOMNodeExtractorConfig<T, Result> {
  isNode: (node: unknown) => node is T;
  transform: (node: T) => Result;
}

const createDOMNodeExtractor = <T, TResult>(
  config: DOMNodeExtractorConfig<T, TResult>
) => {
  return (nodes: unknown[]): TResult[] => {
    return nodes.filter(config.isNode).map(config.transform);
  };
};

it('Should pick up that "extractDivs" is of type "HTMLDivElement[]"', () => {
  const extractDivs = createDOMNodeExtractor({
    isNode: isDivElement,
    transform: (div) => {
      type test1 = Expect<Equal<typeof div, HTMLDivElement>>;
      return div.innerText;
    },
  });

  const divs = extractDivs([document.createElement('div')]);

  type test2 = Expect<Equal<typeof divs, string[]>>;
});

it('Should pick up that "extractBodies" is of type "HTMLBodyElement[]"', () => {
  const extractBodies = createDOMNodeExtractor({
    isNode: isBodyElement,
    transform: (body) => {
      type test1 = Expect<Equal<typeof body, HTMLBodyElement>>;

      return body.bgColor;
    },
  });

  const bodies = extractBodies([document.createElement('body')]);

  type test2 = Expect<Equal<typeof bodies, string[]>>;
});

 

posted @ 2023-02-10 20:38  Zhentiw  阅读(10)  评论(0编辑  收藏  举报