字符串联合的 Typescript 并发症
Typescript complications with string unions
我正在尝试创建一个函数,该函数 returns JSX 取决于 name prop。
这是我的代码:
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 仍会引发错误。我怎样才能 return 没有错误的正确组件?谢谢!
看起来 Ionicons
有超过 3,000 个名称,而 Feather
有 300 多个。如果我用 type="Feather"
调用您的组件并且名称只存在于 Ionicons
?
您的组件的类型使得 name
是一个有效的道具,如果它存在于 Ionicons
或 Feather
上。但这还不够好。我们需要知道该图标存在 在所选图标集 上 。
将道具定义为联合将使错误消失。
function TabBarIcon(props: {
color: string;
} & (
{
name: React.ComponentProps<typeof Ionicons>['name'];
type: 'Ionicons';
} | {
name: React.ComponentProps<typeof Feather>['name'];
type: '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 />;
}
我正在尝试创建一个函数,该函数 returns JSX 取决于 name prop。 这是我的代码:
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 仍会引发错误。我怎样才能 return 没有错误的正确组件?谢谢!
看起来 Ionicons
有超过 3,000 个名称,而 Feather
有 300 多个。如果我用 type="Feather"
调用您的组件并且名称只存在于 Ionicons
?
您的组件的类型使得 name
是一个有效的道具,如果它存在于 Ionicons
或 Feather
上。但这还不够好。我们需要知道该图标存在 在所选图标集 上 。
将道具定义为联合将使错误消失。
function TabBarIcon(props: {
color: string;
} & (
{
name: React.ComponentProps<typeof Ionicons>['name'];
type: 'Ionicons';
} | {
name: React.ComponentProps<typeof Feather>['name'];
type: '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 />;
}