What should one configure for getting auto-suggestions (with types) in the Javascript file?
In other words, given a component written in JS, how to get auto-suggestion of its props (it is possible, please read all the question).
I'm trying to get auto-suggestion for a simple Button component (to get a suggestion of "red" or "blue"), similar to components in 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";
}
See changes here .
// Button.d.ts
import * as React from "react";
declare const Button: React.FC<{
color: "red" | "blue";
}>;
export default Button;
// App.js
const App = () => {
return (
<>
{/* Auto-suggests "red" and "blue" */}
<Button color="red" />
</>
);
};
You need to name the .d.ts
file with the same name as the .js
. Also, you need you declare the Button
, not just the props.
Although @bengr given a great answer, there is an alternative using Typescript in JSDocs, it allows semantic errors in javascript files:
// App.js
// @ts-check
const App = () => {
return (
<>
<Button color="red" />
{/* Shows a WARNING! */}
<Button color={null} />
</>
);
};
// types.ts
import type { CSSProperties, FunctionComponent } from "react";
export type ButtonComponent = FunctionComponent<{color: CSSProperties["color"]}>;
// Button.js
import React from "react";
/**
* @type {import("./types").ButtonComponent}
*/
const Button = ({ color }) => <button style={{ color }}>Button</button>;
export default Button;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.