属性 'counter' 的打字稿错误在类型“{}”.ts 上不存在

typescript error with Property 'counter' does not exist on type '{}'.ts

嗨,我在 js 中有一个工作示例,我正在尝试将其移植到 tsx,但我看到的错误是

属性 'counter' 在多个位置不存在于类型“{}”.ts 中,请参阅下面的代码中的注释 "HERE"

App.tsx

import React from "react";
import { render } from "react-dom";
import Larry from "./larry";
import useCounter from "./use.counter";
import global from "./global";

const App3 = () => {
  global.counter = useCounter();   //<===== HERE 

  return (
    <>
      <Larry />
    </>
  );
};

export default App3;

larry.tsx

import React from "react";
import global from "./global";

export default function Larry() {
  return (
    <div style={{ marginBottom: 20 }}>
      <div>Larry: {global.counter.count}</div> //<===== HERE 
      <div>
        <button onClick={global.counter.increment}>Increment</button> //<===== HERE 
      </div>
    </div>
  );
}

use.counter.tsx

import { useState } from "react";

export default function useCounter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(count + 1);

  return {
    count,
    increment,
  };
}

global.tsx

export default {};

我很困惑为什么它适用于 JS 但不适用于 TSX。请帮助:)

根据建议,我尝试了 "export default {counter: useCounter()}"

然后我能够编译但是在运行时我看到这个错误信息:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at resolveDispatcher (/Users/ka/proje…development.js:1476)
    at Object.useState (/Users/ka/proje…development.js:1507)
    at Object.useCounter [as default] (use.counter.tsx:4)
    at Object.<anonymous> (global.tsx:4)
    at Object.<anonymous> (global.tsx:5)
    at Module._compile (internal/modules/cjs/loader.js:1078)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1108)
    at Module.load (internal/modules/cjs/loader.js:935)
    at Module._load (internal/modules/cjs/loader.js:776)
    at Function.f._load (electron/js2c/asar_bundle.js:5)

如果您只想消除错误,将 global.counter = 更改为 (global as any).counter = 会有所帮助,但如果您打算长期使用 ts,则需要重新考虑您的代码。

关于您的案例和解决方案的更多信息 'any': https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html#sequentially-added-properties

这篇文章是开始从 js 迁移到 ts 的好点子。