概述
我有一个next.js
(反应)TypeScript 项目正在使用styled-components
ThemeProvider
. 我正在尝试对存储基于字体大小的theme
对象进行索引,并按点大小()进行索引。我遇到的问题是我无法根据从组件传递的道具动态设置索引。错误消息、代码示例、尝试的解决方案和观察结果如下rem
strings
integer
错误信息
Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{ 14: string; 12: string; 10: string; }'.
No index signature with a parameter of type 'number' was found on type '{ 14: string; 12: string; 10: string; }'.
代码示例
主题对象类型定义
样式化的.d.ts
import "styled-components";
declare module "styled-components" {
export interface DefaultTheme {
fonts: {
size: {
14: string;
12: string;
10: string;
};
}
}
}
样式化组件theme
对象
主题.ts
import { DefaultTheme } from "styled-components";
const theme: DefaultTheme = {
fonts: {
size: {
14: "0.875rem",
12: "0.75rem",
10: "0.625rem"
},
}
};
export { theme };
样式化组件
组件.ts
import styled from "styled-components";
const StyledThingie = styled('div')`
/*
HERE IS WHERE THIS ISSUE IS
I want to conditionally inject the prop (if fontSize is passed)
into the size index to get the rem-based size, and set a default
font-size if no prop is passed.
props.theme.fonts.size[10] works just fine.
*/
font-size: ${props => (props.fontSize ? props.theme.fonts.size[props.fontSize] : props.theme.fonts.size[10])};
`;
export {
StyledThingie
}
反应功能组件
东西.tsx
import React from "react";
import styled from "styled-components";
import { StyledThingie } from "./components.ts";
const Thingie = styled(StyledThingie)`
display: block;
`;
const ThingieComponent: React.FC<any> = (props) => {
return(
<Thingie fontSize={14}> // HERE IS WHERE I"M PASSING THE PROP
<p>This paragraph should be set to 0.875rem or theme.fonts.size[14] </p>
</Thingie>
);
}
尝试的解决方案
我试图index signature
根据一些TypeScript docs定义一个,但不清楚如何实现它。这是我尝试的:
interface FontSize {
[index: string]: number;
}
export type StyledThingieProps = {
fontSize?: FontSize;
}
const StyledThingie = styled('div')<StyledThingieProps>`
size: ${props => (props.fontSize ? props.theme.fonts.size[props.fontSize] : props.theme.fonts.size[10])};
`;
观察
我的脑袋疼 ... ;)