0

Could you explain why the following does not work?

enum Types {
  T1 = "T1",
  T2 = "T2"
}

const something = {
  bool: true,  // some other initial value
  text: "abc", // some other initial value
  type: Types  // nothing yet, but has to be of type Types
}

const type1: Types = Types.T1  // OK

something.type = Types.T1  // error Type 'Types' is not assignable to type 'typeof Types'.ts(2322)
something.type = type1  // error Type 'Types' is not assignable to type 'typeof Types'.ts(2322)
user1589188
  • 5,316
  • 17
  • 67
  • 130
  • Is this a typo? What exactly is your intent when you write `const something = {type: Types}`? Are you aware that this is just a JavaScript object? It has the same effect (at runtime) as `const something = {}; something.type = Types;`. Are you trying to do that? If so, why? If not, what are you trying to do? What would you like `something` to be initialized to? – jcalz May 03 '21 at 02:16
  • Hmm, maybe you don't quite understand the difference between types and values in TypeScript? Does [this question and its answer](https://stackoverflow.com/questions/50376977/generic-type-to-get-enum-keys-as-union-string-in-typescript) clear anything up? – jcalz May 03 '21 at 02:18
  • @jcalz Hi jcalz, I am trying to define an object `something` that starts with nothing but can have a property `type` that is of type `Types`. I updated my question to show my intention. – user1589188 May 03 '21 at 02:31

1 Answers1

1
const something = {
  bool: true,
  text: "abc",
  type: Types
}

The type of something.type is being inferred to be typeof Types, because you're assigning it the value Types, which is the sole value of type typeof Types. If you want to neglect to assign the value at first, you need to make the type nullable.

const something: {bool: boolean, text: string, type: null | Types} = {
  bool: true,
  text: "abc",
  type: null
}

We need an explicit type signature because, without it, the type of something.type is inferred to be null.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • Ah thank you this means sense. But can I skip the type definitions before the = and just do so inside the object? – user1589188 May 03 '21 at 02:43