Class: Field
Wrapper over a RawField exposing HL7 null/empty discrimination
(isNull), the repetitions tree, and a decoded value getter.
seg.field(3) === seg.field(3): Field instances are referentially stable
per segment position (D-12).
Example
import { parseHL7 } from "@cosyte/hl7";
const msg = parseHL7(raw);
const pid5 = msg.segments("PID")[0]?.field(5);
console.log(pid5?.value); // "Smith": decoded at parse
console.log(pid5?.isNull); // false: HL7 explicit null is "", absent is not
console.log(pid5?.repetitions.length); // 1
Constructors
Constructor
new Field(
raw,enc,position):Field
Internal
Construct a new Field. Called internally by Segment.field(n); user
code should obtain Field instances via msg.segments(type)[i].field(n).
Parameters
raw
enc
position
Returns
Field
Properties
enc
readonlyenc:EncodingCharacters
Internal
The 5 encoding characters for this message. Exposed for composite parsers.
isNull
readonlyisNull:boolean
HL7 null indicator: true iff the underlying field was the two-char literal "".
position
readonlyposition:Hl7Position
Internal
Position of this field in the parent message: used for position-aware error messages.
raw
readonlyraw:RawField
Internal
The full RawField this wrapper wraps. Exposed for composite parsers.
repetitions
readonlyrepetitions: readonlyRawRepetition[]
Reference to the underlying RawField.repetitions (no defensive copy).
Accessors
text
Get Signature
get text():
string
The field's canonical wire text: the full field re-serialized with the active delimiters and re-escaped content (repetitions, components, and subcomponents included). Contrast with value, which returns only the first subcomponent of the first component of the first repetition (decoded once at parse: never re-unescaped).
Use this when a field must be compared or echoed as a whole: e.g.
correlating an ACK's MSA-2 against the inbound MSH-10, where a
vendor-quirk control id containing an unescaped delimiter (ID^X) must
not be truncated to its first component.
Byte-verbatim for parsed content. The parse pipeline stores
decoded content, but also records the original wire bytes of any escape
whose decode is not byte-faithful (RawComponent.rawSubcomponents), so
re-serialization preserves the sender's exact escape bytes: hex escapes
stay hex (A\X41\B, casing intact), and recognize-and-preserve sequences
(\H\, \N, formatting/charset/vendor escapes) re-emit verbatim
rather than as escaped literal text. Delimiter/newline escapes and plain
content round-trip byte-exact via the re-escape path. The only remaining
canonicalization is structural: trailing insignificant empties are
stripped (D-02), and a field built by hand (not parsed) re-escapes its
decoded value since it has no overlay.
MSH-1/MSH-2 caveat. Like value, calling this on MSH-1 or
MSH-2 (the delimiter-definition fields) re-escapes the encoding
characters themselves and produces garbage: those two fields are only
meaningful through Hl7Message.encodingCharacters.
Example
import { parseHL7 } from "@cosyte/hl7";
const msg = parseHL7("MSH|^~\\&|A|B|C|D|20260101||ADT^A01|ID^X|P|2.5\r");
msg.segments("MSH")[0]?.field(10).value; // "ID" (first component only)
msg.segments("MSH")[0]?.field(10).text; // "ID^X" (verbatim wire text)
Returns
string
value
Get Signature
get value():
string
First-repetition, first-component, first-subcomponent value as a decoded
string: unescaped ONCE by the tokenizer on parse, returned verbatim here
(never re-unescaped). Returns "" when the field is
empty or HL7 null. Equivalent to msg.get('SEG.N') for a top-level access.
Example
const pid5 = msg.segments("PID")[0]?.field(5);
// wire "Smith\F\Jr" was decoded at parse → the field separator escape:
console.log(pid5?.value); // "Smith|Jr"
Returns
string
Methods
asCe()
asCe():
CE
Coerce this field's first repetition to a typed CE (Coded Element).
Returns
Example
const code = msg.segments("OBX")[0]?.field(3)?.asCe();
console.log(code?.identifier, code?.text);
asCwe()
asCwe():
CWE
Coerce this field's first repetition to a typed CWE (Coded With
Exceptions).
Returns
Example
const code = msg.segments("OBX")[0]?.field(3)?.asCwe();
console.log(code?.identifier, code?.text);
asCx()
asCx():
CX
Coerce this field's first repetition to a typed CX (Extended Composite
ID). assigningAuthority is a nested HD.
Returns
Example
const mrn = msg.segments("PID")[0]?.field(3)?.asCx();
console.log(mrn?.idNumber, mrn?.assigningAuthority?.namespaceId);
asHd()
asHd():
HD
Coerce this field's first repetition to a typed HD (Hierarchic
Designator).
Returns
Example
const sending = msg.segments("MSH")[0]?.field(3)?.asHd();
console.log(sending?.namespaceId);
asNm()
asNm():
NM
Coerce this field's first repetition to a typed NM (Numeric).
{ raw, value }: value is undefined on non-numeric input.
Returns
Example
const nm = msg.segments("OBX")[0]?.field(5)?.asNm();
console.log(nm?.value);
asPl()
asPl():
PL
Coerce this field's first repetition to a typed PL (Person Location).
facility is a nested HD.
Returns
Example
const loc = msg.segments("PV1")[0]?.field(3)?.asPl();
console.log(loc?.pointOfCare, loc?.room, loc?.facility?.namespaceId);
asSn()
asSn():
SN|undefined
Coerce this field's first repetition to a typed SN (Structured Numeric),
or undefined when the field carries no usable structured-numeric content.
Use for an OBX-5 whose OBX-2 value type is SN (a comparator like >90,
a range like 100-200, or a ratio like 1:128). num1/num2 are
number | undefined (never NaN); the comparator is surfaced only when
SN.1 is a recognized operator.
Returns
SN | undefined
Example
const sn = msg.segments("OBX")[0]?.field(5)?.asSn();
console.log(sn?.comparator, sn?.num1); // ">" 90
asTs()
asTs():
DtmParts
Coerce this field's first repetition to a typed TS (Time Stamp): the
fidelity DtmParts (raw + parts + precision + timezone). valid is
false on unparseable input (no throw). Build an absolute instant only on
explicit request via dtmToDate(ts).
Returns
Example
const ts = msg.segments("MSH")[0]?.field(7)?.asTs();
console.log(ts?.raw, ts?.precision, ts?.hasTimezone);
asXad()
asXad():
XAD
Coerce this field's first repetition to a typed XAD (Extended Address).
Returns
Example
const addr = msg.segments("PID")[0]?.field(11)?.asXad();
console.log(addr?.street, addr?.city, addr?.stateOrProvince);
asXcn()
asXcn():
XCN
Coerce this field's first repetition to a typed XCN (Extended Composite
ID Number and Name for Persons). assigningAuthority is a nested HD.
Common on OBR-16 (ordering provider), PV1-7 (attending doctor), PV1-8
(referring doctor). Empty field → {} (never throws).
Returns
Example
const orderedBy = msg.segments("OBR")[0]?.field(16)?.asXcn();
console.log(orderedBy?.idNumber, orderedBy?.familyName, orderedBy?.identifierTypeCode);
asXpn()
asXpn():
XPN
Coerce this field's first repetition to a typed XPN (Extended Person
Name). Absent components are OMITTED from the result
(exactOptionalPropertyTypes). Not memoized in v1: each call re-parses
(D-09).
Returns
Example
const pid5 = msg.segments("PID")[0]?.field(5);
const name = pid5?.asXpn();
console.log(name?.familyName, name?.givenName);
asXtn()
asXtn():
XTN
Coerce this field's first repetition to a typed XTN (Extended
Telecommunication Number).
Returns
Example
const phone = msg.segments("PID")[0]?.field(13)?.asXtn();
console.log(phone?.telephoneNumber);
render()
render(
opts?):RenderedText
Render this field's formatted text (HL7 v2 §2.7 highlight + formatting
escapes) into a normalized RenderedText display model: plain text
plus highlight-aware runs. A read projection over the field's
byte-verbatim wire text: it never mutates the raw value, and it
never fabricates (an unrenderable escape is preserved + flagged). Use this
to surface a clinical narrative (an NTE / OBX-5 note) to a human without
the raw \.br\ / \H sentinels.
Parameters
opts?
see RenderTextOptions (e.g. a custom line-break string).
Returns
the normalized display model.
Example
const note = msg.segments("OBX")[0]?.field(5);
note?.render().text; // "Specimen received.\nGross exam normal."
empty()
staticempty(_enc):Field
Internal
Return a synthetic empty Field sentinel: used by Segment.field(n) to
honor MODEL-05's "never throws on missing" contract. The returned Field
has isNull === false, repetitions === [], and value === "".
Referentially stable across calls (same instance returned each time).
The enc argument is accepted for API symmetry but ignored: the
synthetic field carries no content, so unescape would be a no-op
regardless of the active encoding characters.
Parameters
_enc
Returns
Field
Example
const empty = Field.empty(msg.encodingCharacters);
console.log(empty.value); // ""