【问题标题】:Issue augmenting the react types in typescript增加打字稿中的反应类型的问题
【发布时间】:2018-10-30 13:21:24
【问题描述】:

我正在尝试添加新的钩子以在 typescript 中做出反应(上次我检查过,它们在 distinctlyTyped 上不可用),但它不起作用。

我创建了一个文件types/react.d.ts,如下所示:

import React from 'react';

declare module 'react' {
  function useState<T>(
    initialState: T | (() => T),
  ): [T, (newState: T | ((oldState: T) => T)) => void];
}

但是当我尝试使用它时,它不起作用。

【问题讨论】:

  • 它对我有用。确保tsconfig.json 中没有阻止types/react.d.ts 加载的files/include/exclude 设置。如果你发布一个重现问题的存储库,我会看看它。
  • 也适合我。

标签: reactjs typescript react-hooks


【解决方案1】:

您可以在此处参考 React Hooks 的流类型 - https://github.com/facebook/flow/pull/7149/

它们应该与 TypeScript 非常相似。

在 Flow 中,它看起来像:

declare type BasicStateAction<S> = (S => S) | S;
declare type Dispatch<A> = A => void;

declare export function useState<S>(
  initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>];

【讨论】:

  • 类型不是问题。增加另一个模块是。
【解决方案2】:

事实证明,问题与 tsconfig.json 配置有关,正如 Matt McCutchen 所建议的那样。

【讨论】:

    猜你喜欢
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 2017-06-24
    • 2021-08-05
    • 2017-09-26
    相关资源
    最近更新 更多