Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions examples/typescript-r4/fhir-types/hl7-fhir-r4-core/Bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@ export interface BundleLink extends BackboneElement {
}

// CanonicalURL: http://hl7.org/fhir/StructureDefinition/Bundle (pkg: hl7.fhir.r4.core#4.0.1)
export interface Bundle extends Resource {
export interface Bundle<T extends Resource = Resource> extends Resource {
resourceType: "Bundle";

entry?: BundleEntry[];
entry?: BundleEntry<T>[];
identifier?: Identifier;
link?: BundleLink[];
signature?: Signature;
Expand Down
41 changes: 41 additions & 0 deletions examples/typescript-r4/resource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,47 @@ test("Bundle with resources", () => {
expect(bundle).toMatchSnapshot();
});

test("Bundle<T> narrows entry resources without type predicates", () => {
// A bundle carrying only Patients and Observations
const patient = createPatient();
assert(patient.id);
const observation = createObservation(patient.id);
const bundle: Bundle<Patient | Observation> = {
resourceType: "Bundle",
type: "transaction",
entry: [
{ fullUrl: `urn:uuid:${patient.id}`, resource: patient },
{ fullUrl: `urn:uuid:${observation.id}`, resource: observation },
],
};

// TS 5.5+ infers the type predicate from the discriminated union — no explicit `r is Observation` needed
const observations: Observation[] = (bundle.entry ?? [])
.map((e) => e.resource)
.filter((r) => r?.resourceType === "Observation");

expect(observations).toHaveLength(1);
expect(observations[0]!.id).toBe("glucose-obs-1");
});

test("Bundle<T> entry type is BundleEntry<T>", () => {
const patient = createPatient();
const entry: BundleEntry<Patient> = { fullUrl: `urn:uuid:${patient.id}`, resource: patient };
// resource is narrowed to Patient, not Resource
expect(entry.resource?.resourceType).toBe("Patient");
});

test("Bundle defaults to Bundle<Resource> (backwards compatible)", () => {
const patient = createPatient();
// No type param — entry.resource is Resource | undefined (original behaviour)
const bundle: Bundle = {
resourceType: "Bundle",
type: "collection",
entry: [{ fullUrl: `urn:uuid:${patient.id}`, resource: patient }],
};
expect(bundle.entry).toHaveLength(1);
});

test("Reference accepts all FHIR literal reference forms", () => {
// Relative reference — still narrowed to the typed form
const relative: Observation["subject"] = { reference: "Patient/123" };
Expand Down
93 changes: 61 additions & 32 deletions src/api/writer-generator/typescript/writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
isChoiceDeclarationField,
isComplexTypeIdentifier,
isLogicalTypeSchema,
isNestedIdentifier,
isPrimitiveIdentifier,
isProfileTypeSchema,
isResourceTypeSchema,
Expand Down Expand Up @@ -41,6 +42,8 @@ export const resolveTsAssets = (fn: string) => {
return Path.resolve(__dirname, "../../../..", "assets", "api", "writer-generator", "typescript", fn);
};

type GenericParam = { name: string; constraint: string };

export type TypeScriptOptions = {
lineWidth?: number;
/** openResourceTypeSet -- for resource families (Resource, DomainResource) use open set for resourceType field.
Expand Down Expand Up @@ -204,53 +207,74 @@ export class TypeScript extends Writer<TypeScriptOptions> {
tsIndex: TypeSchemaIndex,
schema: SpecializationTypeSchema | NestedTypeSchema,
isFamilyType?: (ref: TypeIdentifier) => boolean,
) {
nestedGenericParams: Record<string, GenericParam[]> = {},
): GenericParam[] {
let name: string;
// Generic types: Reference, Coding, CodeableConcept
const genericTypes = ["Reference", "Coding", "CodeableConcept"];
if (genericTypes.includes(schema.identifier.name)) {
const isHardcodedGeneric = genericTypes.includes(schema.identifier.name);
if (isHardcodedGeneric) {
name = `${schema.identifier.name}<T extends string = string>`;
} else {
name = tsResourceName(schema.identifier);
}

// Collect fields whose type is a resource type family (has children)
// Collect type-family fields (e.g. `resource: Resource` -> needs T extends Resource)
// and references to generic nested types (e.g. `entry: BundleEntry` when BundleEntry is generic).
const typeFamilyFields: { fieldName: string; familyTypeName: string }[] = [];
for (const [fieldName, field] of Object.entries(schema.fields ?? {})) {
if (isChoiceDeclarationField(field) || !field.type) continue;
const fieldTypeSchema = tsIndex.resolveType(field.type);
if (
isSpecializationTypeSchema(fieldTypeSchema) &&
(fieldTypeSchema.typeFamily?.resources?.length ?? 0) > 0
) {
typeFamilyFields.push({ fieldName: tsFieldName(fieldName), familyTypeName: field.type.name });
const nestedFields: { fieldName: string; params: GenericParam[] }[] = [];
if (!isHardcodedGeneric) {
for (const [fieldName, field] of Object.entries(schema.fields ?? {})) {
if (isChoiceDeclarationField(field) || !field.type) continue;
const tsName = tsFieldName(fieldName);
if (isNestedIdentifier(field.type)) {
const params = nestedGenericParams[field.type.name];
if (params?.length) nestedFields.push({ fieldName: tsName, params });
continue;
}
const fieldTypeSchema = tsIndex.resolveType(field.type);
if (
isSpecializationTypeSchema(fieldTypeSchema) &&
(fieldTypeSchema.typeFamily?.resources?.length ?? 0) > 0
) {
typeFamilyFields.push({ fieldName: tsName, familyTypeName: field.type.name });
}
}
}

// Build generic params from type-family fields
const genericFieldMap: Record<string, string> = {};
if (!genericTypes.includes(schema.identifier.name) && typeFamilyFields.length > 0) {
const [first, ...rest] = typeFamilyFields;
if (first && rest.length === 0) {
genericFieldMap[first.fieldName] = "T";
name += `<T extends ${first.familyTypeName} = ${first.familyTypeName}>`;
} else {
const params = typeFamilyFields.map((tf) => {
const paramName = `T${uppercaseFirstLetter(tf.fieldName)}`;
genericFieldMap[tf.fieldName] = paramName;
return `${paramName} extends ${tf.familyTypeName} = ${tf.familyTypeName}`;
});
name += `<${params.join(", ")}>`;
// Build generic params from type-family fields, then pass-through nested-type params.
const fieldMap: Record<string, string> = {};
const paramList: GenericParam[] = [];
const [first] = typeFamilyFields;
if (typeFamilyFields.length === 1 && nestedFields.length === 0 && first) {
fieldMap[first.fieldName] = "T";
paramList.push({ name: "T", constraint: first.familyTypeName });
} else {
for (const tf of typeFamilyFields) {
const paramName = `T${uppercaseFirstLetter(tf.fieldName)}`;
fieldMap[tf.fieldName] = paramName;
paramList.push({ name: paramName, constraint: tf.familyTypeName });
}
}
const nestedArgsByField: Record<string, string> = {};
for (const nf of nestedFields) {
for (const np of nf.params) {
if (!paramList.find((p) => p.name === np.name)) paramList.push(np);
}
nestedArgsByField[nf.fieldName] = `<${nf.params.map((p) => p.name).join(", ")}>`;
}
if (!isHardcodedGeneric && paramList.length > 0) {
const declParams = paramList.map((p) => `${p.name} extends ${p.constraint} = ${p.constraint}`);
name += `<${declParams.join(", ")}>`;
}

let extendsClause: string | undefined;
if (schema.base) extendsClause = `extends ${tsNameFromCanonical(schema.base.url)}`;

this.debugComment(schema.identifier);
if (!schema.fields && !extendsClause && !isResourceTypeSchema(schema)) {
this.lineSM(`export type ${name} = object`);
return;
return paramList;
}
this.curlyBlock(["export", "interface", name, extendsClause], () => {
if (isResourceTypeSchema(schema)) {
Expand Down Expand Up @@ -282,12 +306,13 @@ export class TypeScript extends Writer<TypeScriptOptions> {
tsName,
field,
undefined,
genericFieldMap,
fieldMap,
isFamilyType,
);
const optionalSymbol = field.required ? "" : "?";
const arraySymbol = field.array ? "[]" : "";
this.lineSM(`${tsName}${optionalSymbol}: ${tsType}${arraySymbol}`);
const nestedArgs = nestedArgsByField[tsName] ?? "";
this.lineSM(`${tsName}${optionalSymbol}: ${tsType}${nestedArgs}${arraySymbol}`);

if (this.withPrimitiveTypeExtension(schema)) {
if (isPrimitiveIdentifier(field.type)) {
Expand All @@ -296,6 +321,7 @@ export class TypeScript extends Writer<TypeScriptOptions> {
}
}
});
return paramList;
}

withPrimitiveTypeExtension(schema: TypeSchema | NestedTypeSchema): boolean {
Expand All @@ -322,13 +348,16 @@ export class TypeScript extends Writer<TypeScriptOptions> {
tsIndex: TypeSchemaIndex,
schema: SpecializationTypeSchema,
isFamilyType?: (ref: TypeIdentifier) => boolean,
) {
): Record<string, GenericParam[]> {
const nestedGenericParams: Record<string, GenericParam[]> = {};
if (schema.nested) {
for (const subtype of schema.nested) {
this.generateType(tsIndex, subtype, isFamilyType);
const params = this.generateType(tsIndex, subtype, isFamilyType, nestedGenericParams);
nestedGenericParams[subtype.identifier.name] = params;
this.line();
}
}
return nestedGenericParams;
}

generateResourceModule(tsIndex: TypeSchemaIndex, schema: TypeSchema) {
Expand All @@ -347,13 +376,13 @@ export class TypeScript extends Writer<TypeScriptOptions> {
this.generateDisclaimer();
this.generateDependenciesImports(tsIndex, schema);
this.generateComplexTypeReexports(schema);
this.generateNestedTypes(tsIndex, schema, isFamilyType);
const nestedGenericParams = this.generateNestedTypes(tsIndex, schema, isFamilyType);
this.comment(
"CanonicalURL:",
schema.identifier.url,
`(pkg: ${packageMetaToFhir(packageMeta(schema))})`,
);
this.generateType(tsIndex, schema, isFamilyType);
this.generateType(tsIndex, schema, isFamilyType, nestedGenericParams);
this.generateResourceTypePredicate(schema);
});
} else {
Expand Down
72 changes: 72 additions & 0 deletions test/api/write-generator/__snapshots__/typescript.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -2125,3 +2125,75 @@ export { USCoreTribalAffiliationExtensionProfile } from "./Extension_USCoreTriba
export { USCoreVitalSignsProfile } from "./Observation_USCoreVitalSignsProfile";
"
`;

exports[`TypeScript Writer Generator generates Bundle with generic entry type (nested generic propagation) 1`] = `
"// WARNING: This file is autogenerated by @atomic-ehr/codegen.
// GitHub: https://github.com/atomic-ehr/codegen
// Any manual changes made to this file may be overwritten.

import type { BackboneElement } from "../hl7-fhir-r4-core/BackboneElement";
import type { Identifier } from "../hl7-fhir-r4-core/Identifier";
import type { Resource } from "../hl7-fhir-r4-core/Resource";
import type { Signature } from "../hl7-fhir-r4-core/Signature";

import type { Element } from "../hl7-fhir-r4-core/Element";
export type { BackboneElement } from "../hl7-fhir-r4-core/BackboneElement";
export type { Identifier } from "../hl7-fhir-r4-core/Identifier";
export type { Signature } from "../hl7-fhir-r4-core/Signature";

export interface BundleEntry<T extends Resource = Resource> extends BackboneElement {
fullUrl?: string;
link?: BundleLink[];
request?: BundleEntryRequest;
resource?: T;
response?: BundleEntryResponse;
search?: BundleEntrySearch;
}

export interface BundleEntryRequest extends BackboneElement {
ifMatch?: string;
ifModifiedSince?: string;
ifNoneExist?: string;
ifNoneMatch?: string;
method: ("GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "PATCH");
url: string;
}

export interface BundleEntryResponse<T extends Resource = Resource> extends BackboneElement {
etag?: string;
lastModified?: string;
location?: string;
outcome?: T;
status: string;
}

export interface BundleEntrySearch extends BackboneElement {
mode?: ("match" | "include" | "outcome");
score?: number;
}

export interface BundleLink extends BackboneElement {
relation: string;
url: string;
}

// CanonicalURL: http://hl7.org/fhir/StructureDefinition/Bundle (pkg: hl7.fhir.r4.core#4.0.1)
export interface Bundle<T extends Resource = Resource> extends Resource {
resourceType: "Bundle";

entry?: BundleEntry<T>[];
identifier?: Identifier;
link?: BundleLink[];
signature?: Signature;
timestamp?: string;
_timestamp?: Element;
total?: number;
_total?: Element;
type: ("document" | "message" | "transaction" | "transaction-response" | "batch" | "batch-response" | "history" | "searchset" | "collection");
_type?: Element;
}
export const isBundle = (resource: unknown): resource is Bundle => {
return resource !== null && typeof resource === "object" && (resource as {resourceType: string}).resourceType === "Bundle";
}
"
`;
6 changes: 6 additions & 0 deletions test/api/write-generator/typescript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ describe("TypeScript Writer Generator", async () => {
expect(bundleTs).toContain("export interface BundleEntry<T extends Resource = Resource>");
expect(bundleTs).toContain("resource?: T");
});
it("generates Bundle with generic entry type (nested generic propagation)", async () => {
const bundleTs = files["generated/types/hl7-fhir-r4-core/Bundle.ts"];
expect(bundleTs).toContain("export interface Bundle<T extends Resource = Resource>");
expect(bundleTs).toContain("entry?: BundleEntry<T>[]");
expect(bundleTs).toMatchSnapshot();
});
it("generates BundleEntryResponse with generic type-family parameter", async () => {
const bundleTs = files["generated/types/hl7-fhir-r4-core/Bundle.ts"];
expect(bundleTs).toContain("export interface BundleEntryResponse<T extends Resource = Resource>");
Expand Down
Loading