1

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)
3
  • 1
    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? Commented May 3, 2021 at 2:16
  • 1
    Hmm, maybe you don't quite understand the difference between types and values in TypeScript? Does this question and its answer clear anything up? Commented May 3, 2021 at 2: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. Commented May 3, 2021 at 2:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.