如何与JavaScript一起使用TypeScript声明文件

时间:2020-05-21 10:25:32

标签: javascript reactjs typescript declaration

我想将我的JavaScript函数文档分成TypeScript .d.ts文件。

例如:

components/
  Button/
    Button.jsx   # JavaScript component
    Button.d.ts  # TypeScript documentation with prop types

类似,Material UI如何做到这一点。 https://github.com/mui-org/material-ui/tree/master/packages/material-ui/src/Button

我的问题是TypeScript和VSCode无法识别当前JavaScript文件的.d.ts文件。

在我的设置中,我具有以下Button.d.ts文件:

interface Props {
  text: string
  onClick: () => void
}

declare const Button: (props: Props) => Element

export default Button

以及以下Button.jsx文件:

import React from 'react'

const Button = ({ text, onClick }) => {
  return <button onClick={onClick}>{text}</button>
}

export default Button

但是VSCode无法识别组件中的prop类型:

Screenshot


如何设置我的项目(可能是tsconfig.json文件)以接受使用相应的.d.ts文件?

我当前的tsconfig.json配置:

{
  "compilerOptions": {
    "declaration": true,
    "rootDir": "./src",
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "isolatedModules": true,
    "noEmit": true,
    "maxNodeModuleJsDepth": 2
  },
  "include": ["src/**/*"]
}

1 个答案:

答案 0 :(得分:1)

如果要在本地项目中使用它

tsconfig.json中删除"src/**/*",然后添加"src/**/*.d.ts",然后js文件将不会被解析为any类型,并且它们的定义将包括在内:

{
  ...,
  "include": ["src/**/*.d.ts"],
  ...,
}

例如,将.jsx.d.ts以与Button.jsxButton.d.ts相同的名称放入相同的目录。

在任何.ts文件中使用它,例如,如果./src/usage.ts也位于components下,则使用src

import Button from './components/Button/Button';

const b1 = Button({
    text: '123',
    onClick: () => {
        console.log('here');
    },
});

const b2 = Button({
    text: 123, // fails - it's not a string.
    onClick: () => {
        console.log('here');
    },
});

enter image description here

如果您希望将其用作图书馆

您需要在package.json中添加

{
  ...,
  "typings": "index.d.ts",
  ...,
}

,然后在index.d.ts

/// <amd-module name="package-name" />
export * from './other-files-with-declarations';