我想将我的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无法识别.d.ts
当前JavaScript文件的文件。
在我的设置中,我有以下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/**/*"]
}
如果您想在本地项目中使用它
在tsconfig.json
remove "src/**/*"
add中"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';
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句