#TypeScript Type Issue

30 messages · Page 1 of 1 (latest)

unreal wyvern
#

Hello, I'm having an issue which makes my brain hurt... I want that the type of "connection" is either "ITable" or "null" but for some reason it always throws me this error.

Code: https://img.walkaisa.dev/Kik9XWMSdC

Error at "this.connection" (Line: 7): Type 'null' is not assignable to type 'If<Ready, IConnection, null>'.
Error at "this.connection" (Line: 15): Type '{ id: string; timestamp: number; }' is not assignable to type 'If<Ready, IConnection, null>'.

Saturday, April 15, 2023 at 21:02

opal lark
#

@unreal wyvern I'm not sure trying to express the readiness of the database through a generic type param is a good idea.

#

You're trying to assign to a generic conditional type there which isn't really a safe thing to do

unreal wyvern
#

What is even the issue in my code? I really have no plan.

#

@opal lark

opal lark
#

I just don't think generic classes really work the way you're trying to use them.

#

I would probably just have connection be IConnection | null.

#

Or - my preference - not construct the class itself until the connection is ready.

unreal wyvern
opal lark
#

Generics aren't great for trying to express mutable, internal state of classes

#

That's genearlly just not something that's very ergonomic to try to reflect at the type level.

unreal wyvern
#

So you would stay at this one "IConnection | null"?

opal lark
#

Given your current setup, yeah.

#

Like I said, my preferred approach would be to make the connection then build the class.

unreal wyvern
opal lark
#
class Database {
    static connectToDatabase(): Promise<Database> {
         return makeConnection().then(connection => new Database(connection));
    }

    private connection: IConnection;
    constructor(connection: IConnection) {this.connection = connection;}   
}
#

Then things that need a database connection would either just have Database, which would be known to be connected, or Promise<Database> if it's possibly still connecting.

opal lark
#

At least not the kind that involve generics.

unreal wyvern
opal lark
#

I don't know what you mean.

#

That is the issue

unreal wyvern
#

What?

opal lark
#

Exactly.

unreal wyvern
#

I'm confused now.

opal lark
#

I just don't know what you're looking for. The issue is that generic conditional types are not things that are safe to assign to.

#

That's just now how they work.

unreal wyvern
#

Okay