在 Typescript/React 中使用一种或另一种接口类型
Use one or another interface type in Typescript/React
有这种类型:
export interface IMyTypes {
First: {
name: string;
city: string;
country: string;
status: string;
};
Second: {
name: string;
age: number;
height: number;
};
}
这必须在一个组件中使用,但我不能让它接受两者,props 应该是 First 或 Second。
我可以让它为 First 工作:
import { IMyTypes } from '../my-types';
interface MyComponentProps {
componentProps: ComponentProps<IMyTypes['First']>;
}
或第二个:
interface MyComponentProps {
componentProps: ComponentProps<IMyTypes['Second']>;
}
但是无法让它接受一个或另一个,尝试如下但不正确:
interface MyComponentProps {
componentProps: ComponentProps<IMyTypes['First' | 'Second']>;
}
有解决办法吗?
解决问题的方案:
interface MyComponentProps {
componentProps:
| ComponentProps<IMyTypes['First']>
| ComponentProps<IMyTypes['Second']>;
}
有这种类型:
export interface IMyTypes {
First: {
name: string;
city: string;
country: string;
status: string;
};
Second: {
name: string;
age: number;
height: number;
};
}
这必须在一个组件中使用,但我不能让它接受两者,props 应该是 First 或 Second。
我可以让它为 First 工作:
import { IMyTypes } from '../my-types';
interface MyComponentProps {
componentProps: ComponentProps<IMyTypes['First']>;
}
或第二个:
interface MyComponentProps {
componentProps: ComponentProps<IMyTypes['Second']>;
}
但是无法让它接受一个或另一个,尝试如下但不正确:
interface MyComponentProps {
componentProps: ComponentProps<IMyTypes['First' | 'Second']>;
}
有解决办法吗?
解决问题的方案:
interface MyComponentProps {
componentProps:
| ComponentProps<IMyTypes['First']>
| ComponentProps<IMyTypes['Second']>;
}