Factory Pattern With Discriminated Union

Create objects via a factory using discriminated unions for type-safe construction by kind.

TypescriptData Integrity

Code

typescriptsnippet
1 line
type Shape={kind:'circle';radius:number}|{kind:'square';size:number}|{kind:'rect';w:number;h:number};export function createShape(kind:'circle',radius:number):Shape;export function createShape(kind:'square',size:number):Shape;export function createShape(kind:'rect',w:number,h:number):Shape;export function createShape(kind:string,...args:number[]):Shape{switch(kind){case'circle':return{kind:'circle',radius:args[0]};case'square':return{kind:'square',size:args[0]};case'rect':return{kind:'rect',w:args[0],h:args[1]};default:throw new Error('unknown shape');}}export function area(s:Shape):number{switch(s.kind){case'circle':return Math.PI*s.radius**2;case'square':return s.size**2;case'rect':return s.w*s.h;}}

How the snippet works

Factory Pattern With Discriminated Union keeps everything in the functions createShape and area.

Error is not tied to any input check: it fires whenever execution reaches that line.

Using it

The primary signature is export function createShape(kind:'circle',radius:number)

The surface worth importing is createShape; the helpers around it are private to the snippet.

Interactive Tools for This Topic

FAQ

Is there any input checking?
No input check exists: the `Error` fires whenever execution reaches its line, not in response to any data shape.
Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. The file defines `createShape`, `area` at load time.