CharlesStover / reactn

React, but with built-in global state management.
https://www.npmjs.com/package/reactn
MIT License
1.89k stars 85 forks source link

useGlobal() does not compile using TypeScript - Throws TS2345 Error #158

Closed RyanNerd closed 4 years ago

RyanNerd commented 4 years ago

I need to use @ts-ignore to get this to compile

import React, {useGlobal, setGlobal} from 'reactn';

function foo() {
    setGlobal({bar: 'test'});
    // @ts-ignore TS2345: Argument of type '"bar"' is not assignable to parameter of type 'never'.
    const [ bar ] = useGlobal('bar');
}
quisido commented 4 years ago

Check out the TypeScript support section of the README. 🙂

RyanNerd commented 4 years ago

Thanks @CharlesStover but I did create a src/global.d.ts file per the instructions in the README and I'm still needing to use // @ts-ignore to get this to compile. Any ideas why this is not working?

quisido commented 4 years ago

Do you have a custom tsconfig.json file?

RyanNerd commented 4 years ago

@CharlesStover Thanks for your help with this. This is what my tsconfig.json looks like:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}
quisido commented 4 years ago

I am fairly certain that TypeScript does not support global.d.ts files when compilerOptions.isolatedModules is set to true.

Additionally, in a recent project I had to set compilerOptions.baseUrl to "src".

If you find that global.d.ts is incompatible with your project (due to a need for isolatedModules), I'd recommend moving the global state to a Provider, then import the Provider and use its Provider.useGlobal method instead of the default global state.

simonv3 commented 4 years ago

One way around the limitations of the isolatedModules call for me was to create a reactn.d.ts file in a styles folder and put the stuff from the README in there.

src/
 - ...
 - types/
   - reactn.d.ts
   - index.d.ts

That seems to load everything correctly, and typecheck appropriately.