153

I'm working on a project with react using typescript and I'm having a bad time figuring out why this error is happening, basically, I can't use any createContext examples that I found on the internet because of this. This one specifically I got from here: https://github.com/typescript-cheatsheets/react-typescript-cheatsheet I'm trying to use the same that is showing in the Context section.

import * as React from "react";

export function createCtx<A>(defaultValue: A) {
type UpdateType = React.Dispatch<React.SetStateAction<typeof defaultValue>>;
const defaultUpdate: UpdateType = () => defaultValue;
const ctx = React.createContext({
    state: defaultValue,
    update: defaultUpdate
});
function Provider(props: React.PropsWithChildren<{}>) {
    const [state, update] = React.useState(defaultValue);
    return <ctx.Provider value={{ state, update }} {...props} />;
}
return [ctx, Provider] as [typeof ctx, typeof Provider];
}

The issue is that everytime it says that there's this error Cannot find namespace ctx in the line:

        return <ctx.Provider value={{ state, update }} {...props} />;

I'm still not able to figure out why, someone can see if I'm doing something wrong here? This is my tsconfig.json:

{
"compilerOptions": {
"target": "es5",
"lib": [
  "dom",
  "dom.iterable",
  "esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"noImplicitAny": false,
"strictNullChecks": false
},
"include": [
"src"
]
}

Any help would be appreciated!

1
  • It seem the problem is in the configuration file. I was able to compile it on typescript playground. I cannot add the link here as it is too long. Where is you tsconfig.json located? Commented Sep 15, 2019 at 18:44

1 Answer 1

714
+25

Your file extension is most likely .ts instead of .tsx.

Therefore TypeScript is interpreting <ctx.Provider as cast and tries to find a type Provider in the namespace ctx.

Sign up to request clarification or add additional context in comments.

7 Comments

Why does every Tutorial talking about <context.Provider use files like context/xyz.js instead of .jsx?
@Dollique Because typescript and javascript are not the same. Just to simplify javascript is not paying attention to the details but typescript does.
@Rarblack I was asking about js instead of jsx. Many Tutorials use .js files, which is the reason why I used .ts instead of .tsx in my case.
tbh that s a super unclear error message...
You're a legend man!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.