I'm converting my React project to Typescript.
I have this piece of state:
AdminBlogPostContainer.tsx
const [blogPost,setBlogPost] = useState<null | BLOGPOST>(null);
return(
<AdminBlogPostPage
blogPost={blogPost as BLOGPOST}
setBlogPost={setBlogPost}
/>
);
AdminBlogPostPage.tsx
interface AdminBlogPostPage {
blogPost: BLOGPOST,
setBlogPost: // <---- WHAT SHOULD I USE AS TYPE HERE ?
}
const AdminBlogPostPage: React.FC<AdminBlogPostPage> = (props) => {
console.log("Rendering AdminBlogPostPage...");
return(
// ...
);
};
export default AdminBlogPostPage;
This is the error message:

Let's start with some relevant type definitions from @types/react.
declare namespace React {
// ...
type SetStateAction<S> = S | ((prevState: S) => S);
// ...
type Dispatch<A> = (value: A) => void;
// ...
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
// ...
}
From this we can already deduce the type of setBlogPost in the statement
const [blogPost, setBlogPost] = useState<null | BLOGPOST>(null);
which is Dispatch<SetStateAction<null | BLOGPOST>>, but let's break that down to see what each part means.
setBlogPost: (value: null | BLOGPOST | ((prevState: null | BLOGPOST) => null | BLOGPOST)) => void;
Digesting that one piece at a time working from the outside in, we get the following explanation:
setBlogPost: (value: ...) => voidsetBlogPost is a function that accepts a parameter value and returns void.
value: null | BLOGPOST | ((prevState: ...) => null | BLOGPOST)value is either null, a BLOGPOST, or a function that accepts a parameter prevState and returns null or a BLOGPOST.
prevState: null | BLOGPOSTprevState is either null or a BLOGPOST.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With