0

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?

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
  • 1
    Enum values are _numbers_ by default, if you want _string_ enums see https://www.typescriptlang.org/docs/handbook/enums.html#string-enums (playground: https://tsplay.dev/mMRoZW). – jonrsharpe Oct 27 '21 at 13:23
  • @jonrsharpe Thanks, that's the cause of, and solution to the problem. if you add it as an answer I'll accept it. – mikemaccana Oct 27 '21 at 13:27
  • enums are static values, this is not something you can create dynamically. – captain-yossarian from Ukraine Oct 27 '21 at 13:27
  • @Cerbrus Kind of, 'Using string literal types is another alternative' from that question is relevant to this question. if you mark it as dupe that's OK I understand. – mikemaccana Oct 27 '21 at 13:28
  • 1
    The _question_ on the dupe includes the option for string enums, I think the whole thing needs tidying up! – jonrsharpe Oct 27 '21 at 13:29

0 Answers0