我想将我的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类型:
如何设置我的项目(可能是tsconfig.json文件)以接受使用相应的.d.ts文件?
我当前的tsconfig.json配置:
{
"compilerOptions": {
"declaration": true,
"rootDir": "./src",
"allowJs": true,
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"noEmit": true,
"maxNodeModuleJsDepth": 2
},
"include": ["src/**/*"]
}
答案 0 :(得分:1)
如果要在本地项目中使用它
在tsconfig.json
中删除"src/**/*"
,然后添加"src/**/*.d.ts"
,然后js文件将不会被解析为any
类型,并且它们的定义将包括在内:
{
...,
"include": ["src/**/*.d.ts"],
...,
}
例如,将.jsx
和.d.ts
以与Button.jsx
和Button.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';