Reputation: 904
Hi there is a way to add a new type to an existing prop?
export interface ICustomState extends INonIdealStateProps {
icon: 'load';
}
export const CustomState: React.FunctionComponent<ICustomState> = (
props: ICustomState
) => {
//My code
};
I have my custom interface ICustomState
that extends INonIdealStateProps
and I'm trying to add a new type to the icon
prop
that already exists in INonIdealStateProps
but I'm getting this error:
Interface 'ICustomState' incorrectly extends interface 'INonIdealStateProps'.
The original type is:
icon?: IconName | Element
Upvotes: 3
Views: 652
Reputation: 249486
When you create a derived interface your properties can be more specific. So for example if IconName
is just an alias for string
this would be valid:
type IconName = string
export interface INonIdealStateProps {
icon: IconName | Element
}
export interface ICustomState extends INonIdealStateProps {
icon: 'load' | Element;
}
If IconName
is not an alias for string
then you can't really extend the interface in it's current form (this would break the rule that a sub-interface is assignable to the base interface). You could however omit the problematic member from the interface and add it with the new type (although the resulting interface will not be assignable to the INonIdealStateProps
interface)
type IconName = "a" | "b"
export interface INonIdealStateProps {
icon: IconName | Element
}
export interface ICustomState extends Omit<INonIdealStateProps, 'icon'> {
icon: 'load' | INonIdealStateProps['icon']; // | INonIdealStateProps['icon'] adds back the type in the base interface, this is not strictly needed
}
Upvotes: 3