簡體   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