I have the following function:
const UseFeature = ({ name }: { name: string }) => {
const features = useContext(FeatureFlags);
if (features === null) {
throw new Error('You must wrap your components in a FeatureProvider.');
}
return Array.isArray(features) ? features.includes(name) : features[name];
};
export default UseFeature;
I call this function on another component :
const hasV1 = UseFeature('v1');
I get this error which I don't understand
Argument of type 'string' is not assignable to parameter of type '{ name: string; }'.
TS2345
Yet 'V1' is indeed a string element.
Have you ever had this problem ?
CodePudding user response:
V1 is a string but UseFeature wants a { name: string; }
You have two options.
You could change the type when you call UseFeature
const hasV1 = UseFeature({name: 'v1'});
or change the declaration of UseFeature to
const UseFeature = (name: string ) => {
And still call it with const hasV1 = UseFeature('v1');
In this second example you are no longer destructuring an object. With the function using only one property / parameter I prefer the second solution more.
CodePudding user response:
I think it's because UseFeature destructures name, so is expecting that when you call the function. You've just passed a string:
const hasV1 = UseFeature('v1');
It is expecting an object:
const hasV1 = UseFeature({name: 'v1'});
