matrix-js-sdk icon indicating copy to clipboard operation
matrix-js-sdk copied to clipboard

Fix type errors in README.md

Open jameshfisher opened this issue 2 years ago • 2 comments

Most examples in the README have type errors have type errors when using "matrix-js-sdk": "^28.2.0". There are several causes:

  • Passing plain strings (e.g. "Room.timeline") as event names does not type-check, because the event names are defined using a TypeScript enum. Instead, one must use sdk.RoomEvent.Timeline etc.
  • The examples imply callback-based APIs that seem to no longer exist. For example, client.publicRooms does not take a callback; instead it returns a Promise.
  • The examples assume some values that, according to the types, can be null or undefined.
  • The examples use some accessors like client.store.rooms that do not exist in the types; instead one must use getters like client.store.getRooms().

Checklist

  • [ ] Tests written for new code (and old code if feasible)
  • [ ] Linter and other CI checks pass
  • [ ] Sign-off given on the changes (see CONTRIBUTING.md)

This change is marked as an internal change (Task), so will not be included in the changelog.

jameshfisher avatar Oct 02 '23 13:10 jameshfisher

The examples are JS rather than TS where the strings continue to work just fine

t3chguy avatar Oct 02 '23 13:10 t3chguy

The examples are JS rather than TS where the strings continue to work just fine

My assumption is that you want JS that is not just runtime-correct, but also type-correct according to your own typings. If they're not, most people trying to get started will assume (as I did) that the code is broken. (I believe even the developers writing JS will be using the TypeScript typings, because IDEs use these published typings even in JS.)

The approach I took is to fix the examples to work with the typings. The alternative is to fix the types to work with the examples. The problem is that matrix-js-sdk is using TypeScript's enum, which should generally be avoided (for this reason, among others!).

For example, this is how ClientEvent is currently defined:

export enum ClientEvent {
    Sync = "sync",
    Event = "event",
    // ...
    TurnServers = "turnServers",
    TurnServersError = "turnServers.error",
}

Using this definition, this does not type-check:

// Error: Type '"sync"' is not assignable to type 'ClientEvent'
const ev: sdk.ClientEvent = "sync";

If you want this to work, a better definition would be:

export const ClientEvent = {
    Sync: "sync",
    Event: "event",
    // ...
    TurnServers: "turnServers",
    TurnServersError: "turnServers.error",
} as const;

export type ClientEvent = typeof ClientEvent[keyof typeof ClientEvent]; // "sync" | "event" | ... 

So - do the team instead want to fix the types to work with the examples?

jameshfisher avatar Oct 02 '23 21:10 jameshfisher