Reputation: 4299
I have a react component that requires a prop with string
type. I also have a function that returns the string
, it has the type (value: any): string
.
When I am trying to pass it to my component <Component stringProp={myFunction("value")} />
I get the error:
Type '(value: any) => string' is not assignable to type 'string'.ts(2322)
How should I write the type for myFunction
or to use the function in the prop? I don't want to call it outside of the component if possible.
Upvotes: 7
Views: 15214
Reputation: 4272
UPDATE
import React from "react";
export interface MyProps {
some: string;
another: number;
oneMore: string;
}
const MyCom:React.FC<MyProps> = props =>{
...
};
Now you have all them props AND It includes children prop AND default Props as well
import * as React from "react";
export interface MyProps {
some: string;
another: number;
oneMore: string;
}
export function MyComponent (props: MyProps): React.ReactElement<MyProPs> {
const { some, another, oneMore } = props;
return (
<p>{some}</p>
)
}
Upvotes: 0
Reputation: 955
I suggest you use interface
like so because in this way you can handle your prop and you can pass it a function or a string :
interface Props {
YOUR_PROP_NAME : (value? : any) => string | string
};
and use it in your component
const App : React.FC<Props> = (props) => {
return (
<>
{typeof props.YOUR_PROP_NAME === "string" ? <div>{props.YOUR_PROP_NAME}</div> : <div>{props.YOUR_PROP_NAME()}</div>}
</>
);
};
export default App;
Upvotes: 1
Reputation: 6253
Seems to me like your issue is as follows. You have specified that your component accepts a string
as a prop, but you are passing it a function. You would need to updated the props interface to not expect a string, but rather a function which returns a string. It would look something like this.
interface Props {
getString: (value: any) => string;
}
Now your component isn't expecting a string, but rather a function which matched the type you are passing in.
Upvotes: 0