How to use TypeScript declaration files alongside JavaScript

可紊 提交于 2021-02-07 06:36:11

问题


I want to separate my JavaScript function documentation into TypeScript .d.ts files.

For example:

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

Similarly how Material UI does this. https://github.com/mui-org/material-ui/tree/master/packages/material-ui/src/Button

My issue is that TypeScript & VSCode does not recognize the .d.ts file for the current JavaScript file.

In my setup, I have the following Button.d.ts file:

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

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

export default Button

and the following Button.jsx file:

import React from 'react'

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

export default Button

But VSCode is not recognising the prop types in the component:


How can I set up my project (maybe tsconfig.json file) to accept the use of corresponding .d.ts file?

My current tsconfig.json config:

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

回答1:


if you want to use it in your local project

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

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

put .jsx and .d.ts in the same dir under the same name as Button.jsx and Button.d.ts for example.

Use it in any .ts file, for example ./src/usage.ts if components are under src too:

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

If you want to serve it as a library

In your package.json you need to add

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

and then in index.d.ts

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


来源:https://stackoverflow.com/questions/61932377/how-to-use-typescript-declaration-files-alongside-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!