Typescript +React props的 undefined 错误

用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;

图片描述

阅读 2.1k
1 个回答

cap这个方法的参数要改成(text?: string)
因为你的ha本身就是一个可以空的参数
之后return text.toLocaleUpperCase;要加一个if判断一下,并且返回为空的时候的值
所以修改如下:

import React, { FC } from 'react';

interface Props {
    ha?: string;
}
const test: FC<Props> = props => {
    const { ha } = props;
    const cap = (text?: string) => {
        if (!!text) {
            return text.toLocaleUpperCase;
        }
        return 'DEFAULT_TEXT'
    };
    return <div>{cap(ha)}</div>;
};

export default test;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题