如何在JavaScript文件中配置类型以获取自动建议?

在Javascript文件中获取自动建议(带有类型)应该配置什么?


换句话说,给定一个用JS编写的组件,如何获得其道具的自动建议(这是可能的,请阅读所有问题)。


我正在尝试获取简单按钮组件的自动建议(以获取“红色”或“蓝色”的建议),类似于MUI中的组件。


// Would like the IDE so suggest "red" or "blue" on changing color prop

const App = () => {

  return <Button color="red" />;

};

// Button.js

import React from "react";


const Button = ({ color }) => <button style={{ color }}>Button</button>;


export default Button;

// ButtonTypes.d.ts

export interface Button {

  color: "red" | "blue";

}


喵喔喔
浏览 123回答 2
2回答

HUH函数

在此处查看更改。// Button.d.tsimport * as React from "react";declare const Button: React.FC<{&nbsp; color: "red" | "blue";}>;export default Button;// App.jsconst App = () => {&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; {/* Auto-suggests "red" and "blue" */}&nbsp; &nbsp; &nbsp; <Button color="red" />&nbsp; &nbsp; </>&nbsp; );};您需要使用与 相同的名称来命名该文件。此外,您需要声明,而不仅仅是道具。.d.ts.jsButton

守着星空守着你

在JSDoc中使用类型脚本有另一种选择,它允许在javascript文件中出现语义错误:// App.js// @ts-checkconst App = () => {&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; <Button color="red" />&nbsp; &nbsp; &nbsp; {/* Shows a WARNING! */}&nbsp; &nbsp; &nbsp; <Button color={null} />&nbsp; &nbsp; </>&nbsp; );};// types.tsimport type { CSSProperties, FunctionComponent } from "react";export type ButtonComponent = FunctionComponent<{color: CSSProperties["color"]}>;// Button.jsimport React from "react";/**&nbsp;* @type {import("./types").ButtonComponent}&nbsp;*/const Button = ({ color }) => <button style={{ color }}>Button</button>;export default Button;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript