下面是我如何在自己的react应用程序中定义和使用我的类型:
FontSize.ts
const fontSize = {
xs: 'xs',
sm: 'sm',
base: 'base',
lg: 'lg',
xl: 'xl'
}
export default Object.freeze(fontSize);
这是我的简单文本组件:
Text.tsx
import { FontSize } from '@bl/foundation';
interface TextProps {
size?: keyof typeof FontSize,
children: React.ReactNode;
}
const Text:React.FC<TextProps> = ({ size = FontSize.sm, children }) => {
const classNames = `font-size-${size}`;
return <p className={classNames}>
{children}
</p>
}
当我编写组件时:
<Text size={FontSize.lg} > Some text here. </Text>
它在size属性中显示了这个错误:
Type 'string' is not assignable to type '"xs" | "sm" | "lg" | "xl" | "base" | undefined'.
发布于 2022-07-26 00:49:15
创建一个枚举FontSize
(参见下面)来替换fontSize
对象。
Enum:
enum FontSize {
XS = "xs",
SM = "sm",
BASE = "base",
LG = "lg",
XL = "xl",
}
这还允许您删除Object.freeze
函数调用。
然后更改TextProps
接口,使size
的类型为FontSize
(创建的枚举):
interface TextProps {
size?: FontSize,
children: React.ReactNode;
}
https://stackoverflow.com/questions/73120269
复制相似问题