Branded identifiers
Concept and syntax
A branded identifier intersects a primitive with a marker type so that two otherwise compatible identifiers cannot be mixed accidentally. The brand is a compile-time convention, not a runtime property on the primitive. Keep assertions inside validated factories; any or assertions can bypass the brand. The as syntax is a type assertion: it is erased at runtime; here the preceding regular expression checks the identifier format.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
type UserId=string & {readonly brand:"UserId"};function userId(s:string):UserId {if(!/^u[0-9]+$/.test(s)) throw new Error("bad id"); return s as UserId;}function show(id:UserId){return id;}console.log(show(userId("u7")));Expected output:
u7Common mistake
Intentionally invalid; compile separately and do not execute.
type UserId=string & {readonly brand:"UserId"};type OrderId=string & {readonly brand:"OrderId"};function use(id:UserId){}function mix(id:OrderId){use(id);}Expected diagnostic: TS2345. The two markers are incompatible. Use an identifier from the correct validated factory.
Practice and recap
Create an OrderId factory and demonstrate an accidental mix being rejected.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Branded identifiers — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type UserId=string & {readonly brand:"UserId"};function userId(s:string):UserId {if(!/^u[0-9]+$/.test(s)) throw new Error("bad id"); return s as UserId;}function show(id:UserId){return id;}console.log(show(userId("u7")));Which diagnostic and explanation match the rejected example under the lesson settings?
type UserId=string & {readonly brand:"UserId"};type OrderId=string & {readonly brand:"OrderId"};function use(id:UserId){}function mix(id:OrderId){use(id);}