用Styled components时,定义了theme是DefaultTheme, 但是很多都是optional。项目有一个默认的theme,但是有时候需要覆盖默认的主题. theme的类型也是DefaultTheme,这时在使用props.theme.xxx的时候就会出现xxx可能是undefined错误。
export interface DefaultTheme {
colors?: Colors;
global: {
animation?: {
duration: string;
jiggle: {
duration: string;
};
};
borderSize?: {
xsmall: string;
small: string;
medium: string;
large: string;
xlarge: string;
};
下面这种情况也是类似的吧
import React, { FC } from 'react';
interface Props {
ha?: string;
}
const test: FC<Props> = props => {
const { ha } = props;
const cap = (text: string) => {
return text.toLocaleUpperCase;
};
return <div>{cap(ha)}</div>;
};
export default test;
cap这个方法的参数要改成(text?: string)
因为你的ha本身就是一个可以空的参数
之后return text.toLocaleUpperCase;要加一个if判断一下,并且返回为空的时候的值
所以修改如下: