Skip to content

Generated TypeScript message class not compatible with generated message interface #837

@bhouser

Description

@bhouser

protobuf.js version: 6.8.0

Problem:
Message class instances cannot be assigned to interface typed variable (or function parameter);

Generated TypeScript definitions.

    interface IToken {
        message?: google.protobuf.IAny;
    }

    class Token {
        constructor(properties?: core.IToken);
        public message?: (google.protobuf.IAny|null);
        public static encode(message: core.IToken, writer?: $protobuf.Writer): $protobuf.Writer;
        public static encodeDelimited(message: core.IToken, writer?: $protobuf.Writer): $protobuf.Writer;
        public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): core.Token;
        public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): core.Token;
        public static verify(message: { [k: string]: any }): (string|null);
    }

Code resulting in TypeScript Error:

const myEncodedToken = Token.encode(myToken);

TypeScript Error:

Error:(42, 37) TS2345:Argument of type 'Token' is not assignable to parameter of type 'IToken'.
  Types of property 'message' are incompatible.
    Type 'IAny | null | undefined' is not assignable to type 'IAny | undefined'.
      Type 'null' is not assignable to type 'IAny | undefined'.

A similar problem was fixed in response to this issue: #826. The types now correctly reflect that an instantiated message class can have undefined fields. But assignment to the interface (by calling Message.encode for example) is still impossible.

Example generated TypeScript interface which would fix the problem:

    interface IToken {
        message?: google.protobuf.IAny | null;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions