使用 TypeScript 实现 CSS 断点混入的问题

Problem with implementing the CSS breakpoint mixin using TypeScript

基于 https://tobbelindstrom.com/blog/how-to-create-a-breakpoint-mixin-with-styled-components/ 我正尝试在 TypeScript 中做同样的事情,但我无法键入此函数。

import { css } from 'styled-components';
import { breakpoints } from './_variables';

export const respondTo = Object.keys(breakpoints).reduce(
  (accumulator, label) => {
    accumulator[label] = (...args) => css`
      @media (min-width: ${breakpoints[label]}) {
        ${css(...args)};
      }
    `;
    return accumulator;
  },
  {}
);

我试过这样的事情:

export const respondTo = Object.keys(breakpoints).reduce<Record<string, Function>>(
  (accumulator, label) => {
    accumulator[label] = (...args: Array<String>) => css`
      @media (min-width: ${breakpoints[label]}) {
        ${css(...args)};
      }
    `;
    return accumulator;
  },
  {}
);

但它一直在抛出错误。现在,它给了我

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.   No index signature with a parameter of type 'string' was found on type '{}'.  TS7053

breakpoints[label]

这是有效的

import { css } from "styled-components";

const breakpoints = {
  xs: "480px",
  sm: "768px",
  md: "992px",
  lg: "1200px"
};

type cssParams = Parameters<typeof css>;
const keys = Object.keys(breakpoints) as Array<keyof typeof breakpoints>;

export const respondTo = keys.reduce((accumulator, label) => {
  accumulator[label] = (...args: cssParams) => {
    return css`
      @media (min-width: ${breakpoints[label]}) {
        ${css(...args)};
      }
    `;
  };
  return accumulator;
}, {} as Record<keyof typeof breakpoints, Function>);

问题是 breakpoints[label]: Object.keys() returns 输入 string[],所以 label 变成 string,这不是一个有效的键breakpoints.

或者您可以将 breakpoints 重新键入 Record<string, string>

我还添加了 cssParams,这将在解决此问题后帮助您 ;)