Skip to content

SocketData being wrapped with Partial can create the need to use non-null assertions #4537

Closed
@navidmafi

Description

@navidmafi

Is your feature request related to a problem? Please describe.

Socket.IO allows to add arbitrary data to Socket instance with Socket.data which is very nice and handy. the problem arises when using this data in a type-safe manner.
Please take a look at the example below:

In this example, the middleware ensures that the socket connection is authenticated and if it is, it adds some data to socket instance for later usage.
As you can see, the Server object is typed with ISocketData which looks like this :

export interface ISocketData {
        userID: string;
        userName: string;
        isEmailVerified: boolean;
        joinedRoomUUID: string | null;
        joinedRoomInviteCode: string | null;
    }

image

But since Socket.data type is internally wrapped with Partial, undefined type will be added to all of the properties.
This can causes the need to use non-null assertion or any type of TypeAssertion when using any of the properties in Socket.data, since of course Typescript wouldn't know the logical context.

image

Describe the solution you'd like

Not wrapping SocketData with Partial internally. Current codebases will work fine and properties can still have the undefined type by just adding it in type of the value passed to SocketData like below if the business logic or anything requires them to have the undefined type.

image

Describe alternatives you've considered
Using manual assertions introduced in TS 3.7. please check the links below with the first one being the same example said here.

https://twitter.com/NavidMafi/status/1597884685551513600
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions

Additional context
image

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions