【发布时间】:2021-06-20 17:11:19
【问题描述】:
我正在尝试创建一个根据 name 属性返回 JSX 的函数。 这是我的代码:
function TabBarIcon(props: {
name:
| React.ComponentProps<typeof Ionicons>['name'] // 'key' | 'item' | 2000 more...
| React.ComponentProps<typeof Feather>['name']; // 2000 different strings...
color: string;
type: 'Ionicons' | 'Feather';
}) {
if (props.type === 'Ionicons')
return <Ionicons size={30} style={{ marginBottom: -3 }} {...props} />;
else if (props.type === 'Feather')
return <Feather size={30} style={{ marginBottom: -3 }} {...props} />;
else return <View />;
}
TypeScript 会引发错误,因为它不能确定 <Ionicons /> 和 <Feather /> 组件是否包含名称。我试图用 props.type 来解决这个问题,但 TypeScript 仍然会引发错误。如何在没有错误的情况下返回正确的组件?谢谢!
【问题讨论】:
-
能否提供错误信息?
-
请考虑将此处的代码修改为minimal reproducible example,将其放入像The TypeScript Playground 这样的独立IDE 时,可以清楚地表明您的问题。或者,如果这不可能,请考虑提供一个链接,指向正确配置的 Web IDE 项目,以证明您的问题。这将帮助人们解决问题并提高您获得的答案的质量。大概问题是
props不是discriminated union 的形式。 -
这是一个链接,但它给出了不同的错误:snack.expo.io/GsNspaqKf。我设备上的错误是“属性‘名称’的类型不兼容。”
-
看起来 IDE 需要的是 JS 而不是 TS 代码。如果我看不到您所看到的相同问题,那么我很难对它做任何事情。也许您可以解决这个问题,或者尝试将问题减少到没有外部依赖的问题。
标签: reactjs typescript react-native typescript-typings react-typescript