小编Cha*_*uys的帖子

如何为子目录中的模块添加类型定义?

我正在尝试模拟axios使用 using发出的请求nock此集成历史上存在一些问题,但此问题中描述的解决方法有效。当我将 Typescript 引入混合中时,出现了我的问题。虽然axios附带了主库的类型定义文件,但nock集成axios需要从子目录导入,如下所示:

import HttpAdapter from 'axios/lib/adapters/http';
Run Code Online (Sandbox Code Playgroud)

Typescript 编译器抱怨这一行并出现以下错误:

TS7016: Could not find a declaration file for module 'axios/lib/adapters/http'. 'C:/Users/<user>/<project>/node_modules/axios/lib/adapters/http.js' implicitly has an 'any' type.
  Try `npm install @types/axios` if it exists or add a new declaration (.d.ts) file containing `declare module 'axios';`
Run Code Online (Sandbox Code Playgroud)

我该如何修复这个错误?我尝试过各种自定义类型定义的组合,类似于axios

// <project>/src/types/axios.d.ts

declare module 'axios/lib/adapters/http` {
    import { Adapter } from 'axios';

    const HttpAdapter: Adapter;

    export default HttpAdapter;
}
Run Code Online (Sandbox Code Playgroud)

我对 Typescript …

typescript nock axios

5
推荐指数
1
解决办法
4231
查看次数

如何使用类型化上下文提供程序创建通用React组件?

使用React的新上下文API,您可以像这样创建类型化的上下文生产者/消费者:

type MyContextType = string;

const { Consumer, Producer } = React.createContext<MyContextType>('foo');
Run Code Online (Sandbox Code Playgroud)

但是,假设我有一个列出项目的通用组件。

// To be referenced later
interface IContext<ItemType> {
    items: ItemType[];
}

interface IProps<ItemType> {
    items: ItemType[];
}

class MyList<ItemType> extends React.Component<IProps<ItemType>> {
    public render() {
        return items.map(i => <p key={i.id}>{i.text}</p>);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我想将一些自定义组件呈现为列表项,并从中传递属性MyList作为上下文,我将如何实现呢?可能吗


我尝试过的

方法1

class MyList<ItemType> extends React.Component<IProps<ItemType>> {
    // The next line is an error.
    public static context = React.createContext<IContext<ItemType>>({
        items: []
    }
}
Run Code Online (Sandbox Code Playgroud)

这种方法行不通,因为您无法从静态上下文访问类的类型,这很有意义。

方法#2

使用标准上下文模式,我们在模块级别(即不在类内部)创建使用者和生产者。这里的问题是我们必须先创建使用者和生产者,然后才能知道它们的类型参数。

方法3

在Medium上找到了一篇与我想做的事情相对应 …

typescript reactjs

4
推荐指数
4
解决办法
2006
查看次数

标签 统计

typescript ×2

axios ×1

nock ×1

reactjs ×1