Skip to content

Allow fields to be undefined in create(Schema, message) to support exactOptionalPropertyTypes #1423

Description

@chmnchiang

In #1371, the compiler starts emit | undefined because typescript enable exactOptionalPropertyTypes by default starting with 5.9.

But enable exactOptionalPropertyTypes also breaks creating message with field set to true for field without field presence. For example, in protobuf edition 2023.

Here is an example:

import { create } from "@bufbuild/protobuf";
import { TimestampSchema } from "@bufbuild/protobuf/wkt";
 
create(TimestampSchema, {});                   // ok: field omitted
create(TimestampSchema, { nanos: 5 });         // ok
create(TimestampSchema, { nanos: undefined }); // when exactOptionalPropertyTypes is false, OK
// But when exactOptionalPropertyTypes is true, failed with:
// Type '{ nanos: undefined; }' is not assignable to type '{ readonly $typeName?: never; seconds?: bigint; nanos?: number; }' with 'exactOptionalPropertyTypes: true'.
// Consider adding 'undefined' to the types of the target's properties. 

One simple fix will be adding | undefined to the definition of MessageInit. That is

type MessageInit<T extends Message> = T | {
  [P in keyof T as P extends "$unknown" ? never : P]?: P extends "$typeName"
    ? never
    : FieldInit<T[P]> | undefined;
}

Which matches the optional ? placed in the key.

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