I some data in a JSON file (a minimal reproducible example for this Stack Overflow post):
deleteme.json
:
{
"name": "Steve",
"sport": "hiking"
}
I then load that file into my TypeScript app, using it as the value for 'steve' which is of 'Person' type:
deleteme.ts
:
import * as someObject from "./deleteme.json";
enum Sports {
"skiing",
"hiking",
}
interface Person {
name: string;
sport: Sports;
}
const steve = someObject as Person;
console.log(steve);
However this fails because:
Conversion of type '{ name: string; sport: string; }' to type 'Person' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Types of property 'sport' are incompatible.
Type 'string' is not comparable to type 'Sports'.
I can see I need to convert 'hiking' (the string) into the 'hiking' member of the 'Sports' enum. But I'm not sure how!
How do I load JSON as objects with Enums using TypeScript?