繁体   English   中英

typescript 错误与属性“计数器”不存在类型“{}”.ts

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

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

在多个位置的类型“{}”.ts 上不存在属性“计数器”,请参见下面的代码中带有注释“HERE”

应用程序.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;

拉里.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>
  );
}

使用.counter.tsx

import { useState } from "react";

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

  return {
    count,
    increment,
  };
}

全球.tsx

export default {};

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

根据建议,我尝试了“导出默认 {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,则需要重新考虑您的代码。

有关您的案例和“任何”解决方案的更多信息: https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html#sequentially-added-properties

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM