英文:
TypeScript fails to check React
问题
例如,我得到了以下的组件:
const Component = ({
messages,
}: {
messages: ({ text: string; } | undefined)[];
}) => {
return (
<>
{messages.map((message) => (
<div key={message.text}>
{message.text}
</div>
))}
</>
);
};
当我像这样使用它时,它不会抛出错误:
// 第一个示例
<Component messages={[ someBoolean ? "text 1" : undefined, "text 2", ]} />
但是,当我像这样使用它时,它会抛出错误:
// 第二个示例
const messages = [ someBoolean ? "text 1" : undefined, "text 2" ]
<Component messages={messages} />
// 第三个示例
<Component messages={[ someBoolean ? "text 1" : undefined, "text 2" ] as const} />
为什么第一个示例不会抛出错误?我应该在tsconfig中添加一些内容来捕捉此错误吗?
英文:
For example I got the following component:
const Component = ({
messages,
}: {
messages: ({ text: string; } | undefined)[];
}) => {
return (
<>
{messages.map((message) => (
<div key={message.text}>
{message.text}
</div>
))}
</>
);
};
It doesn't throw errors when I use it like this:
// First example
<Component messages={[ someBoolean ? "text 1" : undefined, "text 2", ]} />
However, it throws errors when I use it like this:
// Second example
const messages = [ someBoolean ? "text 1" : undefined, "text 2" ]
<Component messages={messages} />
// Third example
<Component messages={[ someBoolean ? "text 1" : undefined, "text 2" ] as const} />
Why the first example doesn't' throw errors? Should I add some to the tsconfig to catch this error?
答案1
得分: 1
在所有使用messages
数组的地方都应该出现错误。
原因在于{ text: string; }[]
与string[]
之间的类型差异。
TypeScript有一个内部缓存。
对于VisualStudioCode IDE,请按F1
,输入TypeScript: Restart TS server
,然后运行该命令。几秒钟后,您应该看到错误信息。
对于其他IDE,尝试重新启动应用程序。
英文:
There should be an error in every places where you use the messages
array.
The reason is of the difference in types { text: string; }[]
vs string[]
.
TypeScript has an internal cache.
For VisualStudioCode IDE press F1
, type TypeScript: Restart TS server
and run that command. In several seconds you should see your errors.
For other IDEs just try to restart the application.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论