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

How to use TypeScript declaration files alongside JavaScript

我想将我的 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无法识别组件中的道具类型:


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

我当前的 tsconfig.json 配置:

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

如果你想在本地项目中使用它

in tsconfig.json remove "src/**/*" add "src/**/*.d.ts" instead, then js files will not be parsed as any type and their definition will be included:

{
  ...,
  "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');
    },
});

如果你想把它作为一个图书馆

在您的 package.json 中您需要添加

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

然后在 index.d.ts

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