'Conditional type property on generic class

why does this not work??

export class Client<isReady extends boolean = false> {
  user: isReady extends true ? ClientUser : null = null
}

Deno throws this error Type 'null' is not assignable to type 'isReady extends true ? ClientUser : null'.deno-ts(2322) on the user property

I want the user property to be only of type null at some places and only of type ClientUser at some places and I also want it to be initialized with the value as null.



Solution 1:[1]

You could use the ! operator as suffix of user:

export class Client {
  user!: ClientUser
}

But I do not recommend this because you will lose typescript checks.

It is better to use ClientUser | null union, you need the do some null check, but you will keep your code type safe.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nullable