首页 > 解决方案 > 创建递归样式对象时的打字稿问题

问题描述

我需要制作一个递归样式对象,它可以支持样式属性和嵌套格式。

我很难解决这个问题,而且我已经尝试了几乎所有可以在 SO 和 google 上找到的解决方案。

interface Properties {
  border?: string;
  width?: string;
}

//# 1 Type attempt
type TRecursiveProperties = Properties & {
  [index: string]: TRecursiveProperties;
};

//# 2 Interface attempt
interface IRecursiveProperties extends Properties {
  [index: string]: IRecursiveProperties;
}


const test: TRecursiveProperties = {
  border: '1px solid green',
  isActive: {
    border: '2px solid red',
    '&:hover': {
      border: '3px solid blue'
    }
  }
};

我希望 Recursive 属性是一种后备/捕获所有或某种方式来从 Properties 对象中排除键。

我得到的两个错误是

类型别名“TRecursiveProperties”循环引用自身。

“字符串”类型的属性“宽度”不可分配给字符串索引类型“IRecursiveProperties”

有什么想法可以实现吗?

标签: typescript

解决方案


我会这样做:

interface Properties {
  width?: string;
  border?: string;
  [selector: string]: string | Properties | undefined;
}

const myStyles: Properties = {
  'width': '100px',
  ' .child': {
    'width': '200px',
    'border': '1px color blue',
    '&:hover': {
      border: '1px solid aquamarine',
    },
  },
};

在这个打字稿资源:https ://basarat.gitbooks.io/typescript/docs/types/index-signatures.html中,搜索“设计模式:嵌套索引签名”以查看非常相似的示例。


推荐阅读