or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

checker-creation.mddata-validation.mderror-handling.mdindex.mdinterface-method-validation.mdtype-definition-system.md

type-definition-system.mddocs/

0

# Type Definition System

1

2

Comprehensive type definition DSL for creating complex type structures including interfaces, unions, arrays, functions, and enums.

3

4

## Capabilities

5

6

### Basic Type Builders

7

8

Fundamental type construction functions for creating type definitions.

9

10

```typescript { .api }

11

/**

12

* Defines a type name, either built-in or defined in this suite

13

* @param value - Type name string

14

* @returns TName type node

15

*/

16

function name(value: string): TName;

17

18

/**

19

* Type name implementation with recursive type support

20

*/

21

class TName extends TType {

22

constructor(public name: string);

23

getChecker(suite: ITypeSuite, strict: boolean, allowedProps?: Set<string>): CheckerFunc;

24

}

25

26

/**

27

* Defines a literal value type

28

* @param value - The literal value

29

* @returns TLiteral type node

30

*/

31

function lit(value: any): TLiteral;

32

33

/**

34

* Literal value type implementation

35

*/

36

class TLiteral extends TType {

37

public name: string; // JSON.stringify(value)

38

constructor(public value: any);

39

getChecker(suite: ITypeSuite, strict: boolean): CheckerFunc;

40

}

41

42

/**

43

* Defines an array type

44

* @param typeSpec - Type specification for array elements

45

* @returns TArray type node

46

*/

47

function array(typeSpec: TypeSpec): TArray;

48

49

/**

50

* Array type implementation

51

*/

52

class TArray extends TType {

53

public name?: string; // Generated name like "string[]"

54

constructor(public ttype: TType);

55

getChecker(suite: ITypeSuite, strict: boolean): CheckerFunc;

56

}

57

58

/**

59

* Defines a tuple type with fixed element types

60

* @param typeSpec - Type specifications for each tuple position

61

* @returns TTuple type node

62

*/

63

function tuple(...typeSpec: TypeSpec[]): TTuple;

64

65

/**

66

* Tuple type implementation with optional rest parameter support

67

*/

68

class TTuple extends TType {

69

constructor(public ttypes: TType[]);

70

getChecker(suite: ITypeSuite, strict: boolean): CheckerFunc;

71

}

72

```

73

74

**Usage Examples:**

75

76

```typescript

77

import * as t from "ts-interface-checker";

78

79

// Basic types by name

80

const stringType = t.name("string");

81

const numberType = t.name("number");

82

83

// Literal types

84

const trueLiteral = t.lit(true);

85

const fooLiteral = t.lit("foo");

86

const numberLiteral = t.lit(42);

87

88

// Array types

89

const stringArray = t.array("string");

90

const numberArray = t.array("number");

91

const objectArray = t.array(t.iface([], { id: "number" }));

92

93

// Tuple types

94

const coordinate = t.tuple("number", "number");

95

const nameAge = t.tuple("string", "number");

96

const mixed = t.tuple("string", t.lit(42), "boolean");

97

```

98

99

### Union and Intersection Types

100

101

Combine types using union and intersection operations.

102

103

```typescript { .api }

104

/**

105

* Defines a union type (one of several types)

106

* @param typeSpec - Type specifications for union members

107

* @returns TUnion type node

108

*/

109

function union(...typeSpec: TypeSpec[]): TUnion;

110

111

/**

112

* Defines an intersection type (all types simultaneously)

113

* @param typeSpec - Type specifications for intersection members

114

* @returns TIntersection type node

115

*/

116

function intersection(...typeSpec: TypeSpec[]): TIntersection;

117

118

/**

119

* Union type implementation

120

*/

121

class TUnion extends TType {

122

constructor(public ttypes: TType[]);

123

getChecker(suite: ITypeSuite, strict: boolean): CheckerFunc;

124

}

125

126

/**

127

* Intersection type implementation

128

*/

129

class TIntersection extends TType {

130

constructor(public ttypes: TType[]);

131

getChecker(suite: ITypeSuite, strict: boolean, allowedProps?: Set<string>): CheckerFunc;

132

}

133

```

134

135

**Usage Examples:**

136

137

```typescript

138

// Union types

139

const stringOrNumber = t.union("string", "number");

140

const optionalString = t.union("string", "null");

141

const statusType = t.union(t.lit("pending"), t.lit("complete"), t.lit("error"));

142

143

// Complex unions

144

const idType = t.union("string", "number", t.iface([], {

145

type: t.lit("uuid"),

146

value: "string"

147

}));

148

149

// Intersection types

150

const namedObject = t.intersection(

151

t.iface([], { name: "string" }),

152

t.iface([], { id: "number" })

153

);

154

155

// Mixed intersections

156

const timestamped = t.intersection(

157

"MyInterface",

158

t.iface([], {

159

createdAt: "Date",

160

updatedAt: "Date"

161

})

162

);

163

```

164

165

### Interface Types

166

167

Define interface types with properties, inheritance, and index signatures.

168

169

```typescript { .api }

170

/**

171

* Defines an interface type

172

* @param bases - Array of base interface names that this interface extends

173

* @param props - Object mapping property names to type specifications

174

* @returns TIface type node

175

*/

176

function iface(bases: string[], props: {[name: string]: TOptional|TypeSpec}): TIface;

177

178

/**

179

* Defines an optional property in an interface

180

* @param typeSpec - Type specification for the optional property

181

* @returns TOptional type node

182

*/

183

function opt(typeSpec: TypeSpec): TOptional;

184

185

/**

186

* Special key for index signatures in interfaces

187

*/

188

const indexKey: unique symbol;

189

190

/**

191

* Optional property wrapper type

192

*/

193

class TOptional extends TType {

194

constructor(public ttype: TType);

195

getChecker(suite: ITypeSuite, strict: boolean): CheckerFunc;

196

}

197

198

/**

199

* Interface type implementation

200

*/

201

class TIface extends TType {

202

public props: TProp[];

203

constructor(public bases: string[], props: {[name: string]: TOptional|TypeSpec});

204

getChecker(suite: ITypeSuite, strict: boolean, allowedProps?: Set<string>): CheckerFunc;

205

}

206

```

207

208

**Usage Examples:**

209

210

```typescript

211

// Basic interface

212

const User = t.iface([], {

213

name: "string",

214

age: "number",

215

email: t.opt("string") // Optional property

216

});

217

218

// Interface with inheritance

219

const AdminUser = t.iface(["User"], {

220

permissions: t.array("string"),

221

isActive: "boolean"

222

});

223

224

// Interface with index signature

225

const Dictionary = t.iface([], {

226

[t.indexKey]: "string" // [key: string]: string

227

});

228

229

// Complex interface

230

const ApiResponse = t.iface([], {

231

data: "any",

232

status: t.union(t.lit("success"), t.lit("error")),

233

message: t.opt("string"),

234

timestamp: "Date",

235

metadata: t.opt(t.iface([], {

236

requestId: "string",

237

duration: "number"

238

}))

239

});

240

```

241

242

### Function Types

243

244

Define function signatures with parameters and return types.

245

246

```typescript { .api }

247

/**

248

* Defines a function type

249

* @param resultSpec - Return type specification

250

* @param params - Function parameters

251

* @returns TFunc type node

252

*/

253

function func(resultSpec: TypeSpec, ...params: TParam[]): TFunc;

254

255

/**

256

* Defines a function parameter

257

* @param name - Parameter name

258

* @param typeSpec - Parameter type specification

259

* @param isOpt - Whether parameter is optional

260

* @returns TParam parameter definition

261

*/

262

function param(name: string, typeSpec: TypeSpec, isOpt?: boolean): TParam;

263

264

/**

265

* Defines a rest parameter for tuples

266

* @param typeSpec - Type specification for rest elements

267

* @returns RestType definition

268

*/

269

function rest(typeSpec: TypeSpec): RestType;

270

271

/**

272

* Function type implementation

273

*/

274

class TFunc extends TType {

275

constructor(public paramList: TParamList, public result: TType);

276

getChecker(suite: ITypeSuite, strict: boolean): CheckerFunc;

277

}

278

```

279

280

**Usage Examples:**

281

282

```typescript

283

// Basic function

284

const addFunction = t.func("number",

285

t.param("a", "number"),

286

t.param("b", "number")

287

);

288

289

// Function with optional parameters

290

const greetFunction = t.func("string",

291

t.param("name", "string"),

292

t.param("title", "string", true) // Optional

293

);

294

295

// Function returning complex type

296

const fetchUser = t.func(

297

t.iface([], { name: "string", age: "number" }),

298

t.param("id", "string")

299

);

300

301

// Tuple with rest parameters

302

const flexibleTuple = t.tuple("string", "number", t.rest(t.array("boolean")));

303

304

// More complex rest parameter examples

305

const headersTuple = t.tuple("string", t.rest(t.array("string"))); // ["main", ...headers]

306

const coordinatesTuple = t.tuple("number", "number", t.rest(t.array("number"))); // [x, y, ...points]

307

```

308

309

### Rest Parameter Types

310

311

Special type for handling variable-length tuple elements.

312

313

```typescript { .api }

314

/**

315

* Rest parameter type for tuples with variable-length endings

316

*/

317

class RestType extends TType {

318

constructor(typeSpec: TypeSpec);

319

setStart(start: number): void;

320

getChecker(suite: ITypeSuite, strict: boolean): CheckerFunc;

321

}

322

```

323

324

**Usage Examples:**

325

326

```typescript

327

// Rest parameters allow tuples to accept variable numbers of elements

328

const coordinates = t.tuple("number", "number", t.rest(t.array("number")));

329

330

// Valid data:

331

coordinates.check([10, 20]); // OK - just x, y

332

coordinates.check([10, 20, 30]); // OK - x, y, z

333

coordinates.check([10, 20, 30, 40, 50]); // OK - x, y, and additional points

334

```

335

336

### Function Parameter Lists

337

338

Container for function parameter definitions and individual parameter representations.

339

340

```typescript { .api }

341

/**

342

* Function parameter list type

343

*/

344

class TParamList extends TType {

345

constructor(public params: TParam[]);

346

getChecker(suite: ITypeSuite, strict: boolean): CheckerFunc;

347

}

348

349

/**

350

* Function parameter definition

351

*/

352

class TParam {

353

constructor(public name: string, public ttype: TType, public isOpt: boolean);

354

}

355

```

356

357

**Usage Examples:**

358

359

```typescript

360

// TParam and TParamList are typically created by func() and param() functions

361

// but can be accessed when working with TFunc instances

362

363

const addFunc = t.func("number",

364

t.param("a", "number"),

365

t.param("b", "number", true) // Optional parameter

366

);

367

368

// Access parameter information

369

if (addFunc instanceof TFunc) {

370

for (const param of addFunc.paramList.params) {

371

console.log(`Parameter: ${param.name}, Type: ${param.ttype}, Optional: ${param.isOpt}`);

372

// Output:

373

// Parameter: a, Type: [TName object], Optional: false

374

// Parameter: b, Type: [TName object], Optional: true

375

}

376

}

377

378

// Create parameter list directly

379

const paramList = new TParamList([

380

new TParam("name", t.name("string"), false),

381

new TParam("age", t.name("number"), true)

382

]);

383

```

384

385

### Enum Types

386

387

Define enum types with string or numeric values.

388

389

```typescript { .api }

390

/**

391

* Defines an enum type

392

* @param values - Object mapping enum member names to their values

393

* @returns TEnumType type node

394

*/

395

function enumtype(values: {[name: string]: string|number}): TEnumType;

396

397

/**

398

* Defines a literal enum value reference

399

* @param name - Enum type name

400

* @param prop - Enum member name

401

* @returns TEnumLiteral type node

402

*/

403

function enumlit(name: string, prop: string): TEnumLiteral;

404

405

/**

406

* Enum type implementation

407

*/

408

class TEnumType extends TType {

409

constructor(public values: {[name: string]: string|number});

410

getChecker(suite: ITypeSuite, strict: boolean): CheckerFunc;

411

}

412

413

/**

414

* Enum literal reference implementation

415

*/

416

class TEnumLiteral extends TType {

417

constructor(public enumName: string, public prop: string);

418

getChecker(suite: ITypeSuite, strict: boolean): CheckerFunc;

419

}

420

```

421

422

**Usage Examples:**

423

424

```typescript

425

// Numeric enum

426

const Direction = t.enumtype({

427

Up: 1,

428

Down: 2,

429

Left: 3,

430

Right: 4

431

});

432

433

// String enum

434

const Color = t.enumtype({

435

Red: "red",

436

Green: "green",

437

Blue: "blue"

438

});

439

440

// Mixed enum

441

const Status = t.enumtype({

442

Inactive: 0,

443

Active: "active",

444

Pending: "pending"

445

});

446

447

// Enum literal references

448

const upDirection = t.enumlit("Direction", "Up");

449

const redColor = t.enumlit("Color", "Red");

450

451

// Using enum literals in unions

452

const primaryColors = t.union(

453

t.enumlit("Color", "Red"),

454

t.enumlit("Color", "Green"),

455

t.enumlit("Color", "Blue")

456

);

457

```

458

459

### Built-in Types

460

461

Pre-defined basic types available in the type system.

462

463

```typescript { .api }

464

/**

465

* Built-in type suite containing fundamental JavaScript/TypeScript types

466

*/

467

const basicTypes: ITypeSuite;

468

469

/**

470

* Basic type implementation for built-in JavaScript/TypeScript types

471

*/

472

class BasicType extends TType {

473

constructor(validator: (value: any) => boolean, message: string);

474

getChecker(suite: ITypeSuite, strict: boolean): CheckerFunc;

475

}

476

```

477

478

The `basicTypes` suite includes:

479

- `any`, `unknown` - Universal types

480

- `number`, `string`, `boolean`, `symbol` - Primitive types

481

- `object`, `null`, `undefined`, `void`, `never` - Object and empty types

482

- `Date`, `RegExp` - Built-in object types

483

- `Buffer` - Node.js Buffer type (available only in Node.js environments)

484

- Typed arrays: `Int8Array`, `Uint8Array`, `Float32Array`, etc.

485

- `ArrayBuffer` - Binary data buffer

486

487

**Usage Examples:**

488

489

```typescript

490

import { basicTypes } from "ts-interface-checker";

491

492

// Basic types are automatically included in createCheckers

493

// You can also reference them explicitly

494

const anyType = basicTypes.any;

495

const dateType = basicTypes.Date;

496

const bufferType = basicTypes.Buffer; // Available in Node.js

497

498

// Using built-in types in definitions

499

const TimestampedData = t.iface([], {

500

data: "any",

501

timestamp: "Date",

502

buffer: "Buffer" // References built-in Buffer type

503

});

504

```

505

506

### Interface Property Definitions

507

508

Representation of interface properties with their type and optional status.

509

510

```typescript { .api }

511

/**

512

* Defines a property in an interface

513

*/

514

class TProp {

515

constructor(public name: string, public ttype: TType, public isOpt: boolean);

516

}

517

```

518

519

**Usage Examples:**

520

521

```typescript

522

// TProp instances are typically created internally by the iface() function

523

// but can be accessed when working with TIface instances

524

525

const userInterface = t.iface([], {

526

name: "string",

527

age: "number",

528

email: t.opt("string")

529

});

530

531

// Access properties from a TIface instance

532

if (userInterface instanceof TIface) {

533

for (const prop of userInterface.props) {

534

console.log(`Property: ${prop.name}, Optional: ${prop.isOpt}`);

535

// Output:

536

// Property: name, Optional: false

537

// Property: age, Optional: false

538

// Property: email, Optional: true

539

}

540

}

541

```

542

543

### Type Specification Format

544

545

The `TypeSpec` type allows both TType instances and string references.

546

547

```typescript { .api }

548

/**

549

* Type specification - either a TType instance or string name reference

550

*/

551

type TypeSpec = TType | string;

552

```

553

554

**Usage Examples:**

555

556

```typescript

557

// Using string references

558

const userRef = t.iface([], {

559

name: "string", // String reference to built-in type

560

profile: "UserProfile" // String reference to custom type

561

});

562

563

// Using TType instances

564

const userDirect = t.iface([], {

565

name: t.name("string"), // TType instance

566

profile: t.name("UserProfile") // TType instance

567

});

568

569

// Mixed usage (common pattern)

570

const mixedInterface = t.iface([], {

571

id: "number", // String reference

572

data: t.union("string", "object"), // TType instance

573

optional: t.opt("boolean") // TType instance with opt wrapper

574

});

575

```