or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

additional-namespaces.mdadvanced-types.mdbasic-types.mdcompilation.mdindex.mdjavascript-types.mdtransforms.mdvalue-operations.md

value-operations.mddocs/

0

# Value Operations

1

2

Runtime functions for validation, transformation, and manipulation of values against TypeBox schemas. The Value namespace provides comprehensive tools for working with data at runtime.

3

4

## Capabilities

5

6

### Validation Operations

7

8

#### Check Function

9

10

Returns boolean indicating if value matches schema.

11

12

```typescript { .api }

13

/**

14

* Returns boolean if value matches schema

15

* @param schema - Schema to validate against

16

* @param value - Value to validate

17

* @returns True if value matches schema

18

*/

19

function Check<T extends TSchema>(schema: T, value: unknown, references?: TSchema[]): value is Static<T>;

20

```

21

22

**Usage Examples:**

23

24

```typescript

25

import { Type, Value } from "@sinclair/typebox";

26

27

const User = Type.Object({

28

name: Type.String(),

29

age: Type.Number()

30

});

31

32

const data1 = { name: "Alice", age: 25 };

33

const data2 = { name: "Bob", age: "30" };

34

35

console.log(Value.Check(User, data1)); // true

36

console.log(Value.Check(User, data2)); // false (age is string, not number)

37

```

38

39

#### Assert Function

40

41

Asserts value matches schema, throws on failure.

42

43

```typescript { .api }

44

/**

45

* Asserts value matches schema, throws on failure

46

* @param schema - Schema to validate against

47

* @param value - Value to validate

48

* @throws ValueError if validation fails

49

*/

50

function Assert<T extends TSchema>(schema: T, value: unknown, references?: TSchema[]): asserts value is Static<T>;

51

```

52

53

**Usage Examples:**

54

55

```typescript

56

try {

57

Value.Assert(User, { name: "Alice", age: 25 });

58

// Value is now typed as { name: string, age: number }

59

} catch (error) {

60

console.error("Validation failed:", error.message);

61

}

62

```

63

64

### Value Creation

65

66

#### Create Function

67

68

Creates default values from schemas.

69

70

```typescript { .api }

71

/**

72

* Creates default values from schemas

73

* @param schema - Schema to create value from

74

* @returns Default value matching schema structure

75

*/

76

function Create<T extends TSchema>(schema: T, references?: TSchema[]): Static<T>;

77

```

78

79

**Usage Examples:**

80

81

```typescript

82

const User = Type.Object({

83

name: Type.String({ default: "Anonymous" }),

84

age: Type.Number({ default: 0 }),

85

isActive: Type.Boolean({ default: true }),

86

tags: Type.Array(Type.String(), { default: [] })

87

});

88

89

const defaultUser = Value.Create(User);

90

// Result: { name: "Anonymous", age: 0, isActive: true, tags: [] }

91

92

// For types without defaults

93

const SimpleUser = Type.Object({

94

name: Type.String(),

95

age: Type.Number()

96

});

97

98

const simpleDefault = Value.Create(SimpleUser);

99

// Result: { name: "", age: 0 }

100

```

101

102

#### Default Function

103

104

Applies default values from schema to existing data.

105

106

```typescript { .api }

107

/**

108

* Applies default values from schema

109

* @param schema - Schema containing default values

110

* @param value - Value to apply defaults to

111

* @returns Value with defaults applied

112

*/

113

function Default<T extends TSchema>(schema: T, value: unknown): Static<T>;

114

```

115

116

**Usage Examples:**

117

118

```typescript

119

const partialUser = { name: "Alice" };

120

const completeUser = Value.Default(User, partialUser);

121

// Result: { name: "Alice", age: 0, isActive: true, tags: [] }

122

```

123

124

### Value Transformation

125

126

#### Cast Function

127

128

Casts value to match schema structure, converting compatible types.

129

130

```typescript { .api }

131

/**

132

* Casts value to match schema structure

133

* @param schema - Target schema

134

* @param value - Value to cast

135

* @returns Value cast to match schema

136

*/

137

function Cast<T extends TSchema>(schema: T, value: unknown): Static<T>;

138

```

139

140

**Usage Examples:**

141

142

```typescript

143

const NumberSchema = Type.Number();

144

145

// String to number conversion

146

const result1 = Value.Cast(NumberSchema, "123");

147

// Result: 123

148

149

const result2 = Value.Cast(NumberSchema, "invalid");

150

// Result: 0 (fallback for invalid conversion)

151

152

// Object casting

153

const User = Type.Object({

154

name: Type.String(),

155

age: Type.Number()

156

});

157

158

const userData = { name: "Alice", age: "25", extra: "ignored" };

159

const castUser = Value.Cast(User, userData);

160

// Result: { name: "Alice", age: 25 }

161

```

162

163

#### Clean Function

164

165

Removes properties not defined in schema.

166

167

```typescript { .api }

168

/**

169

* Removes properties not defined in schema

170

* @param schema - Schema defining allowed properties

171

* @param value - Value to clean

172

* @returns Value with only schema-defined properties

173

*/

174

function Clean<T extends TSchema>(schema: T, value: unknown): unknown;

175

```

176

177

**Usage Examples:**

178

179

```typescript

180

const User = Type.Object({

181

name: Type.String(),

182

age: Type.Number()

183

});

184

185

const dirtyData = {

186

name: "Alice",

187

age: 25,

188

password: "secret",

189

internal: true

190

};

191

192

const cleanData = Value.Clean(User, dirtyData);

193

// Result: { name: "Alice", age: 25 }

194

```

195

196

#### Convert Function

197

198

Converts values to match schema requirements.

199

200

```typescript { .api }

201

/**

202

* Converts values to match schema requirements

203

* @param schema - Target schema

204

* @param value - Value to convert

205

* @returns Converted value

206

*/

207

function Convert<T extends TSchema>(schema: T, value: unknown): Static<T>;

208

```

209

210

### Value Comparison

211

212

#### Equal Function

213

214

Deep equality comparison for values.

215

216

```typescript { .api }

217

/**

218

* Deep equality comparison for values

219

* @param left - First value

220

* @param right - Second value

221

* @returns True if values are deeply equal

222

*/

223

function Equal(left: unknown, right: unknown): boolean;

224

```

225

226

**Usage Examples:**

227

228

```typescript

229

const obj1 = { name: "Alice", tags: ["user", "admin"] };

230

const obj2 = { name: "Alice", tags: ["user", "admin"] };

231

const obj3 = { name: "Bob", tags: ["user"] };

232

233

console.log(Value.Equal(obj1, obj2)); // true

234

console.log(Value.Equal(obj1, obj3)); // false

235

236

// Works with nested objects and arrays

237

const nested1 = { user: { profile: { name: "Alice" } } };

238

const nested2 = { user: { profile: { name: "Alice" } } };

239

console.log(Value.Equal(nested1, nested2)); // true

240

```

241

242

#### Hash Function

243

244

Generates hash codes for values.

245

246

```typescript { .api }

247

/**

248

* Generates hash codes for values

249

* @param value - Value to hash

250

* @returns Hash code as number

251

*/

252

function Hash(value: unknown): number;

253

```

254

255

**Usage Examples:**

256

257

```typescript

258

const user1 = { name: "Alice", age: 25 };

259

const user2 = { name: "Alice", age: 25 };

260

const user3 = { name: "Bob", age: 30 };

261

262

const hash1 = Value.Hash(user1);

263

const hash2 = Value.Hash(user2);

264

const hash3 = Value.Hash(user3);

265

266

console.log(hash1 === hash2); // true (same content)

267

console.log(hash1 === hash3); // false (different content)

268

```

269

270

### Value Manipulation

271

272

#### Clone Function

273

274

Deep clones values with schema awareness.

275

276

```typescript { .api }

277

/**

278

* Deep clones values with schema awareness

279

* @param value - Value to clone

280

* @returns Deep clone of value

281

*/

282

function Clone<T>(value: T): T;

283

```

284

285

**Usage Examples:**

286

287

```typescript

288

const original = {

289

user: { name: "Alice", tags: ["admin"] },

290

settings: { theme: "dark" }

291

};

292

293

const cloned = Value.Clone(original);

294

cloned.user.name = "Bob";

295

cloned.user.tags.push("user");

296

297

console.log(original.user.name); // "Alice" (unchanged)

298

console.log(original.user.tags); // ["admin"] (unchanged)

299

console.log(cloned.user.name); // "Bob"

300

console.log(cloned.user.tags); // ["admin", "user"]

301

```

302

303

#### Mutate Function

304

305

Mutates values using edit operations.

306

307

```typescript { .api }

308

/**

309

* Mutates values using edit operations

310

* @param value - Value to mutate

311

* @param edits - Array of edit operations

312

* @returns Mutated value

313

*/

314

function Mutate(value: Mutable, edits: Edit[]): void;

315

316

interface Edit {

317

type: 'insert' | 'update' | 'delete';

318

path: string;

319

value?: unknown;

320

}

321

322

type Mutable<T = any> = { -readonly [K in keyof T]: T[K] };

323

```

324

325

**Usage Examples:**

326

327

```typescript

328

const data = { users: [{ name: "Alice" }, { name: "Bob" }] };

329

330

const edits = [

331

{ type: 'update', path: '/users/0/name', value: 'Alice Smith' },

332

{ type: 'insert', path: '/users/-', value: { name: 'Charlie' } },

333

{ type: 'delete', path: '/users/1' }

334

];

335

336

const result = Value.Mutate(data, edits);

337

// Result: { users: [{ name: "Alice Smith" }, { name: "Charlie" }] }

338

```

339

340

### Delta Operations

341

342

#### Diff Function

343

344

Computes differences between values.

345

346

```typescript { .api }

347

/**

348

* Computes differences between values

349

* @param left - Original value

350

* @param right - Modified value

351

* @returns Array of edit operations representing the difference

352

*/

353

function Diff(left: unknown, right: unknown): Edit[];

354

```

355

356

**Usage Examples:**

357

358

```typescript

359

const original = { name: "Alice", age: 25, city: "NYC" };

360

const modified = { name: "Alice Smith", age: 26 };

361

362

const diff = Value.Diff(original, modified);

363

// Result: [

364

// { type: 'update', path: '/name', value: 'Alice Smith' },

365

// { type: 'update', path: '/age', value: 26 },

366

// { type: 'delete', path: '/city' }

367

// ]

368

```

369

370

#### Patch Function

371

372

Applies patches to values.

373

374

```typescript { .api }

375

/**

376

* Applies patches to values

377

* @param value - Value to patch

378

* @param edits - Array of edit operations to apply

379

* @returns Patched value

380

*/

381

function Patch<T>(value: T, edits: Edit[]): T;

382

```

383

384

### Data Parsing

385

386

#### Parse Function

387

388

Parses and validates values from JSON.

389

390

```typescript { .api }

391

/**

392

* Parses and validates values from JSON

393

* @param schema - Schema to validate against

394

* @param value - JSON string or parsed value to validate

395

* @returns Parsed and validated value

396

* @throws ValueError if parsing or validation fails

397

*/

398

function Parse<T extends TSchema>(schema: T, value: string | unknown): Static<T>;

399

```

400

401

**Usage Examples:**

402

403

```typescript

404

const User = Type.Object({

405

name: Type.String(),

406

age: Type.Number()

407

});

408

409

// Parse from JSON string

410

const jsonString = '{"name":"Alice","age":25}';

411

const user1 = Value.Parse(User, jsonString);

412

// Result: { name: "Alice", age: 25 }

413

414

// Parse from object

415

const userObj = { name: "Bob", age: 30 };

416

const user2 = Value.Parse(User, userObj);

417

// Result: { name: "Bob", age: 30 }

418

419

// Throws on invalid data

420

try {

421

Value.Parse(User, '{"name":"Alice","age":"25"}'); // age is string

422

} catch (error) {

423

console.error("Parse failed:", error.message);

424

}

425

```

426

427

### Transform Operations

428

429

#### Encode Function

430

431

Encodes values using schema transforms.

432

433

```typescript { .api }

434

/**

435

* Encodes values using schema transforms

436

* @param schema - Transform schema

437

* @param value - Value to encode

438

* @returns Encoded value

439

*/

440

function Encode<T extends TSchema>(schema: T, value: Static<T>): unknown;

441

```

442

443

#### Decode Function

444

445

Decodes transformed values to original form.

446

447

```typescript { .api }

448

/**

449

* Decodes transformed values to original form

450

* @param schema - Transform schema

451

* @param value - Value to decode

452

* @returns Decoded value

453

*/

454

function Decode<T extends TSchema>(schema: T, value: unknown): Static<T>;

455

```

456

457

**Usage Examples:**

458

459

```typescript

460

// Transform that converts Date to/from ISO string

461

const DateTransform = Type.Transform(Type.String())

462

.Decode(value => new Date(value))

463

.Encode(value => value.toISOString());

464

465

const now = new Date();

466

const encoded = Value.Encode(DateTransform, now);

467

// Result: "2024-01-15T10:30:00.000Z"

468

469

const decoded = Value.Decode(DateTransform, encoded);

470

// Result: Date object

471

```

472

473

## Error Handling

474

475

```typescript { .api }

476

interface ValueError extends Error {

477

type: ValueErrorType;

478

schema: TSchema;

479

path: string;

480

value: unknown;

481

message: string;

482

}

483

484

enum ValueErrorType {

485

ArrayContainsNonNumericIndex,

486

ArrayExpected,

487

ArrayItemMissing,

488

ArrayItemCountMinimum,

489

ArrayItemCountMaximum,

490

ArrayItemNotUnique,

491

BooleanExpected,

492

DateExpected,

493

FunctionExpected,

494

IntegerExpected,

495

LiteralValueExpected,

496

NeverExpected,

497

NullExpected,

498

NumberExpected,

499

ObjectExpected,

500

ObjectRequiredPropertyMissing,

501

ObjectAdditionalPropertiesNotPermitted,

502

ObjectPropertyCountMinimum,

503

ObjectPropertyCountMaximum,

504

StringExpected,

505

StringFormatInvalid,

506

StringLengthMinimum,

507

StringLengthMaximum,

508

StringPatternMismatch,

509

UnionExpected,

510

UndefinedExpected,

511

UnknownValue,

512

ValueCheckFailed

513

}

514

515

class ValueErrorIterator implements IterableIterator<ValueError> {

516

[Symbol.iterator](): IterableIterator<ValueError>;

517

next(): IteratorResult<ValueError>;

518

}

519

520

/**

521

* Returns iterator of validation errors

522

* @param schema - Schema to validate against

523

* @param value - Value to validate

524

* @returns Iterator of validation errors

525

*/

526

function Errors<T extends TSchema>(schema: T, value: unknown): ValueErrorIterator;

527

```

528

529

**Usage Examples:**

530

531

```typescript

532

const User = Type.Object({

533

name: Type.String({ minLength: 2 }),

534

age: Type.Number({ minimum: 0 }),

535

email: Type.String({ format: 'email' })

536

});

537

538

const invalidData = { name: "A", age: -5, email: "invalid-email" };

539

540

for (const error of Value.Errors(User, invalidData)) {

541

console.log(`${error.path}: ${error.message}`);

542

}

543

// Output:

544

// /name: String length minimum 2

545

// /age: Number minimum 0

546

// /email: String format 'email' invalid

547

```