I know that this has been asked-and-answered in What is the TypeScript equivalent of "PropTypes.oneOf" (restrict a variable to subset of values), but I have a case where I don't feel like the answer solves my issue yet.
I am working on converting a project from JavaScript to Typescript. In one React component, a JSON file is imported. One of the props in the component must be one of the keys of this JSON:
import React from "react"
import PropTypes from "prop-types"
import myData from "./myData.json"
const dataKeys = Object.keys(myData)
function MyComponent({myType, ...}) { ... }
MyComponent.propTypes = {
myType: PropTypes.oneOf(dataKeys).isRequired,
...
}
I now want to convert MyComponent into Typescript, so I'm going to remove PropTypes and create a Props interface based off of the existing propTypes. The thing is, I am unsure how to convert PropTypes.oneOf
which is built off of an existing variable, especially one that depends on an import of a JSON file. Normally, I would use a union of string literals or an enum type. What are my options in this case?
Yes, I have allowSyntheticDefaultImports
enabled in tsconfig.json
.