1

I am trying to limit the possible values of singleType variable to LANGUAGES, SCIENCE and FICTION instead of an open string using an enum

export enum BookType {
  LANGUAGES = "LANGUAGES",
  SCIENCE = "SCIENCE",
  FICTION = "FICTION",
}

const singleType: BookType = 'SCIENCE'

export interface UserBooks {
  name: string
  type: BookType
}

const fullBook: UserBooks = {
  name: 'Some string',
  type: 'SCIENCE'
}

I am getting this errors:

enter image description here

const singleType: BookType
'singleType' is declared but its value is never read.ts(6133)
Type '"SCIENCE"' is not assignable to type 'BookType'.ts(2322)

enter image description here

(property) UserBooks.type: BookType
Type '"SCIENCE"' is not assignable to type 'BookType'.ts(2322)
section.ts(92, 3): The expected type comes from property 'type' which is declared here on type 'UserBooks'
LuisEnMarroquin
  • 1,609
  • 1
  • 14
  • 26
  • 1
    Is this a typo? Why `BookSubjects` and not `BookType`? The name `BookSubjects` is not defined anywhere in your code, and that seems to be the error. Could you [edit] to fix the typo? – jcalz Nov 15 '22 at 03:32
  • 1
    Enum values are supposed to be opaque; if you're using an enum, you should only refer to the values via the enum keys. Inversely, if you want to refer to the values directly, you shouldn't be using an enum and instead could use a union of string literals. See [this playground link](https://tsplay.dev/mppbMm) for the possibilities. Does that fully address your question? If so I'll write up an answer explaining; if not, what am I missing? (Please mention @jcalz to notify me if you reply) – jcalz Nov 15 '22 at 03:36
  • @jcalz Yes, it was a typo, it's fixed now – LuisEnMarroquin Nov 15 '22 at 07:43
  • @jcalz "if you want to refer to the values directly, you shouldn't be using an enum and instead could use a union of string literals" I think that it makes sense but I wanted to find some way I can convert an enum to the format that you used It's possible to do something like: `ReturnType` ? – LuisEnMarroquin Nov 15 '22 at 08:05
  • Just use `BookType.SCIENCE`. – Etienne de Martel Nov 15 '22 at 15:38
  • That's an off-label use of `enum`s. *Why* do you want that? Still, if that's your question (which you should probably [edit] into the text of the post) then it's a duplicate of [this one](https://stackoverflow.com/questions/52393730/typescript-string-literal-union-type-from-enum) and you should look there instead. – jcalz Nov 15 '22 at 18:11

0 Answers0