【问题标题】:Typescript transform indexed object literal without losing intellisense打字稿转换索引对象文字而不丢失智能感知
【发布时间】:2020-12-16 15:45:30
【问题描述】:

我似乎无法弄清楚让智能感知在我用来定义 CSS 规则的索引对象文字和使用该对象的 css 生成函数返回的对象之间保持工作的魔法咒语。

这是我的伪代码:

type Style = { [key: string]: [keyof CSSStyleDeclaration, string] };

const GenerateCss = (css: Style) => {
  // ...generate css and return an object like this:
  // {
  //   smallFont: 'smallFont',
  //   bigFont: 'bigFont'
  // }
};

const css: Style = {
  smallFont: ['fontSize', '12px'],
  bigFont: ['fontSize', '18px'],
};

结果: 我需要在css 上打字,所以我得到了各种CSSStyleDeclaration 的智能感知,但随后我失去了css 上结果键的智能感知。我觉得答案就在这里:JavaScript to TypeScript: Intellisense and dynamic members,但似乎无法重构它并使其工作。

【问题讨论】:

    标签: typescript generics dynamic key


    【解决方案1】:
    export const style = <T>(
      rules: {
        [key in keyof T]: [keyof CSSStyleDeclaration, string];
      }
    ): {
      [key in keyof T]: keyof CSSStyleDeclaration;
    } => {
      const css: any = {};
      const styles: string[] = [];
      Object.entries(rules).forEach(([k, v]: [string, Atom]) => {
        const declaration = `.${k}{${(<string>v[0])
          .replace(/([A-Z])/g, '-$1')
          .toLowerCase()}:${v[1]}}`;
        css[k] = k;
        styles.push(declaration);
      });
      CreateStyleSheet(styles.join(''));
      return css;
    };
    

    const styles = style({
      cursor_pointer: ['cursor', 'pointer'],
      fs_l: ['fontSize', '18px'],
      fs_m: ['fontSize', '16px'],
      fs_xl: ['fontSize', '24px'],
    });
    

    作品,欢迎评论。

    【讨论】:

      猜你喜欢
      • 2016-04-28
      • 2020-10-04
      • 1970-01-01
      • 2021-09-02
      • 2017-06-28
      • 1970-01-01
      • 2017-06-18
      • 2013-12-25
      • 2019-12-11
      相关资源
      最近更新 更多