Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
4827da2
TS: propagate generic type params through nested type references
ryukzak Apr 22, 2026
f3bbf64
TS: regenerate Bundle and add Bundle<T> demo tests
ryukzak Apr 22, 2026
01bf5df
test: add Bundle<T> propagation unit test and fix no-predicate demo
ryukzak Apr 28, 2026
55cd8dc
ref: inline generic-info computation in TS writer
ryukzak Apr 28, 2026
95d03f6
test: snapshot Bundle.ts with generic propagation
ryukzak Apr 28, 2026
1a90da8
ref: unify generic-contribution loop in TS writer
ryukzak Apr 29, 2026
cbd2d5e
test: snapshot Coding, CodeableConcept, BundleEntry generic emit
ryukzak Apr 29, 2026
8ace59c
TypeSchema/TS: store generic params on NestedTypeSchema
ryukzak Apr 29, 2026
bc08557
test: update snapshots and assertions for nested generic propagation
ryukzak Apr 29, 2026
9486952
TypeSchema/TS: name passthrough generic params by deep source field
ryukzak May 1, 2026
96f46e7
test: update snapshots for sourceField-based generic naming
ryukzak May 1, 2026
c94847f
TypeSchema/TS: switch generic param naming to T1/T2/...
ryukzak May 1, 2026
69a111f
test: update snapshots for T1/T2 generic naming
ryukzak May 1, 2026
c54b9ae
TypeSchema/TS: unify generic info on all specialization schemas
ryukzak May 1, 2026
0aa42c1
test: update CDA + introspection snapshots for unified generic IR
ryukzak May 1, 2026
dd8e406
TypeSchema/TS: rename GenericParam.{name,sourceField} → {typeVar,path}
ryukzak May 1, 2026
e3307b7
test: update introspection snapshots for typeVar/path field rename
ryukzak May 1, 2026
59a1c5a
TypeSchema/TS: import generic constraint types and skip hardcoded spe…
ryukzak May 1, 2026
ae2551c
test: update CDA snapshot — Base imported via generic constraint deps
ryukzak May 1, 2026
34b7a5d
TS: regenerate R4 + US Core examples
ryukzak May 1, 2026
9f1df64
ref: inline per-field generic substitution in TS writer
ryukzak May 1, 2026
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
10 changes: 5 additions & 5 deletions examples/typescript-r4/fhir-types/hl7-fhir-r4-core/Bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ 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 {
export interface BundleEntry<T1 extends Resource = Resource, T2 extends Resource = Resource> extends BackboneElement {
fullUrl?: string;
link?: BundleLink[];
request?: BundleEntryRequest;
resource?: T;
response?: BundleEntryResponse;
resource?: T1;
response?: BundleEntryResponse<T2>;
search?: BundleEntrySearch;
}

Expand Down 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<T1 extends Resource = Resource, T2 extends Resource = Resource> extends Resource {
resourceType: "Bundle";

entry?: BundleEntry[];
entry?: BundleEntry<T1, T2>[];
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
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,13 @@ export class observation_vitalsignsProfile {
return profile;
}

static is (resource: unknown) : resource is Observation {
if (typeof resource !== "object" || resource === null) return false;
const r = resource as { resourceType?: string; meta?: { profile?: string[] } };
if (r.resourceType !== "Observation") return false;
return (r.meta?.profile ?? []).includes(observation_vitalsignsProfile.canonicalUrl);
}

static apply (resource: Observation) : observation_vitalsignsProfile {
ensureProfile(resource, observation_vitalsignsProfile.canonicalUrl);
resource.category = ensureSliceDefaults(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ export class USCoreEthnicityExtensionProfile {
return profile;
}

static is (resource: unknown) : resource is Extension {
if (typeof resource !== "object" || resource === null) return false;
return (resource as { url?: string }).url === USCoreEthnicityExtensionProfile.canonicalUrl;
}

static apply (resource: Extension) : USCoreEthnicityExtensionProfile {
resource.url = USCoreEthnicityExtensionProfile.canonicalUrl;
Object.assign(resource, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ export class USCoreIndividualSexExtensionProfile {
return profile;
}

static is (resource: unknown) : resource is Extension {
if (typeof resource !== "object" || resource === null) return false;
return (resource as { url?: string }).url === USCoreIndividualSexExtensionProfile.canonicalUrl;
}

static apply (resource: Extension) : USCoreIndividualSexExtensionProfile {
resource.url = USCoreIndividualSexExtensionProfile.canonicalUrl;
Object.assign(resource, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ export class USCoreInterpreterNeededExtensionProfile {
return profile;
}

static is (resource: unknown) : resource is Extension {
if (typeof resource !== "object" || resource === null) return false;
return (resource as { url?: string }).url === USCoreInterpreterNeededExtensionProfile.canonicalUrl;
}

static apply (resource: Extension) : USCoreInterpreterNeededExtensionProfile {
resource.url = USCoreInterpreterNeededExtensionProfile.canonicalUrl;
Object.assign(resource, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ export class USCoreRaceExtensionProfile {
return profile;
}

static is (resource: unknown) : resource is Extension {
if (typeof resource !== "object" || resource === null) return false;
return (resource as { url?: string }).url === USCoreRaceExtensionProfile.canonicalUrl;
}

static apply (resource: Extension) : USCoreRaceExtensionProfile {
resource.url = USCoreRaceExtensionProfile.canonicalUrl;
Object.assign(resource, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ export class USCoreTribalAffiliationExtensionProfile {
return profile;
}

static is (resource: unknown) : resource is Extension {
if (typeof resource !== "object" || resource === null) return false;
return (resource as { url?: string }).url === USCoreTribalAffiliationExtensionProfile.canonicalUrl;
}

static apply (resource: Extension) : USCoreTribalAffiliationExtensionProfile {
resource.url = USCoreTribalAffiliationExtensionProfile.canonicalUrl;
Object.assign(resource, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,13 @@ export class USCoreBloodPressureProfile {
return profile;
}

static is (resource: unknown) : resource is Observation {
if (typeof resource !== "object" || resource === null) return false;
const r = resource as { resourceType?: string; meta?: { profile?: string[] } };
if (r.resourceType !== "Observation") return false;
return (r.meta?.profile ?? []).includes(USCoreBloodPressureProfile.canonicalUrl);
}

static apply (resource: Observation) : USCoreBloodPressureProfile {
ensureProfile(resource, USCoreBloodPressureProfile.canonicalUrl);
Object.assign(resource, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ export class USCoreBodyWeightProfile {
return profile;
}

static is (resource: unknown) : resource is Observation {
if (typeof resource !== "object" || resource === null) return false;
const r = resource as { resourceType?: string; meta?: { profile?: string[] } };
if (r.resourceType !== "Observation") return false;
return (r.meta?.profile ?? []).includes(USCoreBodyWeightProfile.canonicalUrl);
}

static apply (resource: Observation) : USCoreBodyWeightProfile {
ensureProfile(resource, USCoreBodyWeightProfile.canonicalUrl);
Object.assign(resource, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ export class USCoreVitalSignsProfile {
return profile;
}

static is (resource: unknown) : resource is Observation {
if (typeof resource !== "object" || resource === null) return false;
const r = resource as { resourceType?: string; meta?: { profile?: string[] } };
if (r.resourceType !== "Observation") return false;
return (r.meta?.profile ?? []).includes(USCoreVitalSignsProfile.canonicalUrl);
}

static apply (resource: Observation) : USCoreVitalSignsProfile {
ensureProfile(resource, USCoreVitalSignsProfile.canonicalUrl);
resource.category = ensureSliceDefaults(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ export class USCorePatientProfile {
return profile;
}

static is (resource: unknown) : resource is Patient {
if (typeof resource !== "object" || resource === null) return false;
const r = resource as { resourceType?: string; meta?: { profile?: string[] } };
if (r.resourceType !== "Patient") return false;
return (r.meta?.profile ?? []).includes(USCorePatientProfile.canonicalUrl);
}

static apply (resource: Patient) : USCorePatientProfile {
ensureProfile(resource, USCorePatientProfile.canonicalUrl);
return new USCorePatientProfile(resource);
Expand Down
87 changes: 50 additions & 37 deletions src/api/writer-generator/typescript/writer.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import * as Path from "node:path";
import { fileURLToPath } from "node:url";
import { uppercaseFirstLetter } from "@root/api/writer-generator/utils";
import { Writer, type WriterOptions } from "@root/api/writer-generator/writer";
import {
type CanonicalUrl,
isChoiceDeclarationField,
isComplexTypeIdentifier,
isLogicalTypeSchema,
isNestedTypeSchema,
isPrimitiveIdentifier,
isProfileTypeSchema,
isResourceTypeSchema,
Expand Down Expand Up @@ -41,6 +41,13 @@ export const resolveTsAssets = (fn: string) => {
return Path.resolve(__dirname, "../../../..", "assets", "api", "writer-generator", "typescript", fn);
};

const leafOf = (path: string[]): string => path[path.length - 1] ?? "";

// Schemas that the TS writer renders with a hardcoded `<T extends string>` generic — their IR
// `generic.params` (if any, computed via structural propagation) must be ignored at reference sites
// so we don't emit `<T>` args clashing with the hardcoded `T extends string` declaration.
const TS_HARDCODED_GENERIC_NAMES = new Set(["Reference", "Coding", "CodeableConcept"]);

export type TypeScriptOptions = {
lineWidth?: number;
/** openResourceTypeSet -- for resource families (Resource, DomainResource) use open set for resourceType field.
Expand Down Expand Up @@ -204,44 +211,50 @@ export class TypeScript extends Writer<TypeScriptOptions> {
tsIndex: TypeSchemaIndex,
schema: SpecializationTypeSchema | NestedTypeSchema,
isFamilyType?: (ref: TypeIdentifier) => boolean,
) {
): void {
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)
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 });
// Generic params come from the IR (populated for all generic-bearing schemas, top-level + nested).
// Hardcoded TS specials (Reference/Coding/CodeableConcept) get their `<T extends string>` above.
const params = isHardcodedGeneric ? [] : (schema.generic?.params ?? []);

// Per-field substitutions: walk fields once, deciding for each whether its type substitutes
// with a schema param (introduce) or its reference appends args (passthrough). Aligning by
// leaf segment of the param's `path` matches deep origins across nesting hops.
const fieldMap: Record<string, string> = {};
const nestedArgsByField: Record<string, string> = {};
if (!isHardcodedGeneric) {
for (const [fieldName, field] of Object.entries(schema.fields ?? {})) {
if (isChoiceDeclarationField(field) || !field.type) continue;
const target = tsIndex.resolveType(field.type);
if (!target || TS_HARDCODED_GENERIC_NAMES.has(target.identifier.name)) continue;
const tsName = tsFieldName(fieldName);
const targetParams =
isNestedTypeSchema(target) || isSpecializationTypeSchema(target)
? target.generic?.params
: undefined;
if (targetParams?.length) {
const args = targetParams.map(
(tp) => params.find((q) => leafOf(q.path) === leafOf(tp.path))?.typeVar ?? tp.typeVar,
);
nestedArgsByField[tsName] = `<${args.join(", ")}>`;
} else if (isSpecializationTypeSchema(target) && (target.typeFamily?.resources?.length ?? 0) > 0) {
const p = params.find((q) => leafOf(q.path) === fieldName);
if (p) fieldMap[tsName] = p.typeVar;
}
}
}

// 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(", ")}>`;
}
if (!isHardcodedGeneric && params.length > 0) {
const declParams = params.map((p) => `${p.typeVar} extends ${p.constraint.name} = ${p.constraint.name}`);
name += `<${declParams.join(", ")}>`;
}

let extendsClause: string | undefined;
Expand Down Expand Up @@ -282,12 +295,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 Down Expand Up @@ -322,12 +336,11 @@ export class TypeScript extends Writer<TypeScriptOptions> {
tsIndex: TypeSchemaIndex,
schema: SpecializationTypeSchema,
isFamilyType?: (ref: TypeIdentifier) => boolean,
) {
if (schema.nested) {
for (const subtype of schema.nested) {
this.generateType(tsIndex, subtype, isFamilyType);
this.line();
}
): void {
if (!schema.nested) return;
for (const subtype of schema.nested) {
this.generateType(tsIndex, subtype, isFamilyType);
this.line();
}
}

Expand Down
21 changes: 21 additions & 0 deletions src/typeschema/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,10 +218,30 @@ interface PrimitiveTypeSchema {
dependencies?: TypeIdentifier[];
}

export type GenericParam = {
typeVar: string;
constraint: TypeIdentifier;
/** Path from this schema down to the typeFamily-rooted field that introduces the param.
* Single segment for a direct introduce (e.g. `["outcome"]` on `BundleEntryResponse`);
* carrier fields are prepended as the param surfaces through passthrough (e.g.
* `["response", "outcome"]` on `BundleEntry`, `["entry", "response", "outcome"]` on
* `Bundle`). Used to align passthrough args across nesting hops. */
path: string[];
};

/** Generic params a schema exposes — populated during index build (after
* `populateTypeFamily`). Each param either binds directly to a field whose type is a
* type-family root (e.g. `BundleEntry.resource: Resource` → T extends Resource) or
* is inherited from a generic-bearing field's target (passthrough). */
export type GenericInfo = {
params: GenericParam[];
};

export interface NestedTypeSchema {
identifier: NestedIdentifier;
base: TypeIdentifier;
fields: Record<string, Field>;
generic?: GenericInfo;
}

export interface ProfileTypeSchema {
Expand Down Expand Up @@ -299,6 +319,7 @@ type SpecializationTypeSchemaBody = {
dependencies?: Identifier[];
/** Transitive children grouped by kind (e.g. Resource → { resources: [DomainResource, Patient, …] }) */
typeFamily?: TypeFamily;
generic?: GenericInfo;
};

export type TypeFamily = {
Expand Down
Loading
Loading