I have a React component authored in JavaScript and published to an npm repository. This component uses the prop-types library to do runtime type checking.
Some of the consumers of this component use TypeScript, and would like type definitions for the component and its props. I'm willing to add an index.d.ts file to my project with type declarations, but since the component already declares the accepted types for the props with prop-types, I'd like to re-use those and not have to maintain types in two different source files.
I know that @types/prop-types adds a utility type, InferProps, that can convert a propTypes object into a usable TypeScript type. But when I attempt to use that within my index.d.ts file, the imported propTypes object is typed as any!
src/MyComponent.js
import React from 'react';
import PropTypes from 'prop-types';
const MyComponent ({color, quantity}) => <p>Color was {color}, quantity: {quantity}</p>;
MyComponent.propTypes = {
color: PropTypes.string,
quantity: PropTypes.number
};
export default MyComponent;
@types/index.d.ts
import React from 'react';
import PropTypes from 'prop-types';
import MyComponent from '../src';
declare const MyComponentType: React.FC<
PropTypes.InferProps<
typeof MyComponent.propTypes
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this always seems to resolve to `any`
>
>;
export default MyComponentType;
Is it possible to import JavaScript code in a TypeScript declaration file? What am I missing?