【问题标题】:How to get the node_modules package types in Typescript如何在 Typescript 中获取 node_modules 包类型
【发布时间】:2020-07-19 20:50:03
【问题描述】:

我正在使用带有 Typescript 的 NativeBase(包名无关紧要)。

我正在创建一个包装 NativeBase TextInput 的简单输入组件。我添加了一些自己的属性并将所有其他属性传播到 NativeBase TextInput。 这意味着 props 对象应该包含我的自定义属性和 NativeBase TextInput。

我的问题是:如何在不复制 NativePase 属性的情况下通过打字稿正确描述它?

import { Input } from 'native-base';

type Props = {
  // my custom prop
  style: object;
  // props from NativeBase
  onFocus?: () => void;
  onBlur?: () => void;
}

export class TextInput extends Component<Props, State> {


  render() {
    // without these callbacks in Props typescript will complain
    const { style, onFocus, onBlur, ...otherProps } = this.props;

    return (
      <Input style={this.getStyle()} {...otherProps}/>
    );
  }

}

我尝试使用 type intersection 但它不起作用,因为 Input 通常不是“类型”;

type Props = Input & {
  // my custom prop
  style: object;
}

另外,我尝试通过 typeof 提取输入类型。没有帮助。

type Props = typeof Input & {
  // my custom prop
  style: object;
}

那么有没有一种方法可以避免复制粘贴我想使用的包可能的道具?

感谢您的帮助!

【问题讨论】:

    标签: reactjs typescript react-native types native-base


    【解决方案1】:

    如果您想向第三方 JavaScript 包添加类型,您可以创建 TypeScript 类型定义。这些是您可能在某些项目中看到的.d.ts files

    有一个 Github 存储库,称为 DefinitiveTyped,它带有许多 JavaScript 模块的第三方类型定义。 They also have a guide how to write and use your own type definition file.

    【讨论】:

    • 嗨 Mikko。感谢您的回答,但实际上他们有。它只是没有被他们的 index.file 导出。我只能导入组件的实现。但是我不能像 props 类型等那样使用它,所以我需要用我的一些来复制组件 props 类型定义。
    猜你喜欢
    • 2019-12-05
    • 1970-01-01
    • 2016-06-03
    • 2019-05-15
    • 2020-04-13
    • 2022-11-10
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多