【发布时间】:2021-05-20 19:30:22
【问题描述】:
我将一个可以是字符串或对象的道具传递给反应功能组件,下面是一个示例。 它无需打字稿即可工作。但是,当我添加打字稿时,它似乎不明白道具(例如下面的 helpMessage)可以是字符串或对象。
我收到此错误
TS2339: Property 'message' does not exist on type 'string | HelpMessage'. Property 'message' does not exist on type 'string'.
import React, { FC } from 'react';
interface HelpMessage {
headerText?: string;
footerText?: string;
message?: string;
}
interface FieldProps {
name: string;
helpMessage?: string | HelpMessage;
}
const ConditionalPropsComponent: FC<FieldProps> = ({ name, helpMessage }) => {
const helpMessageIsString = typeof helpMessage === 'string';
const helpText =
helpMessage && helpMessageIsString ? helpMessage : helpMessage?.message;
return (
<div>
{helpText && !helpMessageIsString && (
<div>
<p>{helpMessage?.headerText}</p>
<p>{helpMessage?.message}</p>
<p>{helpMessage?.footerText}</p>
</div>
)}
{helpText && helpMessageIsString && <p>{helpText}</p>}
</div>
);
};
export default ConditionalPropsComponent;
错误出现在下面屏幕截图中红色摆动线的位置:
我创建了一个代码沙箱,以便您查看问题。 https://codesandbox.io/s/github/nfabacus/React-typescript-dynamic-type-issue/tree/main/?file=/src/index.tsx:217-226
基本上,将条件提取到const helpMessageIsString = typeof helpMessage === 'string'; 会引发类型错误,但如果我将它们中的每一个替换为typeof helpMessage === 'string',错误就会消失,但这是重复的..
同样,下面的工作但感觉很hacky - helpMessage 要么是HelpMessage 要么是未定义的。当我传递字符串时,它既不是 HelpMessage 对象也不是未定义的,但打字稿不会抱怨..这很奇怪。
interface HelpMessage {
headerText?: string;
footerText?: string;
message?: string;
}
interface FieldProps {
name: string;
helpMessage?: HelpMessage;
}
const ConditionalPropsComponent: React.FC<FieldProps> = ({
name,
helpMessage
}) => {
const helpMessageIsString = typeof helpMessage === 'string';
const helpText = helpMessageIsString ? helpMessage : helpMessage?.message;
....
Typescript 很棒,但是在这种特殊情况下,我对 Typescript 感到有些失望,如果没有好的解决方案...
【问题讨论】:
-
尝试把它放在
if块中,编译器可能会中断它。在任何情况下,您都可以在 TS Playground 中制作可重现的示例并向我们展示错误。 -
简单解决界面HelpMessage { headerText?: string;页脚文本?:字符串;消息?:字符串;帮助文本?:字符串; } 接口 FieldProps { 名称:字符串;帮助信息?:帮助信息; } if( helpText ){ }else{ } 基本上打字稿不允许更改类型。使用未知数的第二种解决方案,然后对模型使用类型转换
-
谢谢,但有什么办法可以使用某种类型的打字稿条件来解决这个问题?
标签: reactjs typescript types react-props