3

I'm attempting to create a class with a generic parameter that extends type boolean. I've tried to make this generic parameter accessible at runtime by assigning it to a property like so:

class Example<T extends boolean> {
    foo: T = true;
}

The base class declaration works, but the line initializing foo yields the error:

Type 'boolean' is not assignable to type 'T'.
  'boolean' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'boolean'.

This doesn't make much sense to me. What other type could T be that extends but does not fall under true | false? Why does the possibility that it could be another type prevent it from being initialized as a boolean?

1
  • 2
    What should new Example<false>().foo be? According to the types it's false, but according to your initializer, it's true. That's the problem and why you can't do it. Commented Dec 5, 2022 at 16:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.