Skip to content

default value

awekrx edited this page May 29, 2026 · 1 revision

default-value

Import

import { defaultValue } from '@dev-suite/decorators/default-value'

Category

  • property

Use Case

Provide default property value when field is unset.

Replaces

  • Constructor field default boilerplate
  • Getter-based lazy init guards

Example 1

Without decorator

class SessionState {
  token?: string;

  getToken() {
    if (!this.token) this.token = 'guest';
    return this.token;
  }
}

With decorator

import { defaultValue } from '@dev-suite/decorators/default-value';

class SessionState {
  @defaultValue('guest')
  token!: string;
}

Why better

  • Centralizes cross-cutting behavior.
  • Method/class/property code stays focused on domain logic.

Example 2

Without decorator

class MetricsContext {
  correlationId?: string;

  ensureId() {
    if (!this.correlationId) this.correlationId = crypto.randomUUID();
    return this.correlationId;
  }
}

With decorator

import { defaultValue } from '@dev-suite/decorators/default-value';

class MetricsContext {
  @defaultValue(() => crypto.randomUUID())
  correlationId!: string;
}

Why better

  • Second scenario reuses same policy without duplication.
  • Behavior is more consistent and easier to audit.

Clone this wiki locally