or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# rtts_assert

1

2

rtts_assert is a runtime type assertion library designed for Traceur-compiled JavaScript applications. It provides comprehensive type checking and validation capabilities for both primitive and complex types, including custom type definitions and integration with Traceur's type annotation system.

3

4

## Package Information

5

6

- **Package Name**: rtts-assert

7

- **Package Type**: npm

8

- **Language**: JavaScript (ES6) with Traceur

9

- **Installation**: `npm install rtts-assert`

10

11

## Core Imports

12

13

```javascript

14

import { assert } from "rtts-assert";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { assert } = require("rtts-assert");

21

```

22

23

## Basic Usage

24

25

```javascript

26

import { assert } from "rtts-assert";

27

28

// Basic type checking with primitive values

29

assert.type("hello", assert.string);

30

assert.type(42, assert.number);

31

assert.type(true, assert.boolean);

32

33

// Custom class type checking

34

class User {}

35

const user = new User();

36

assert.type(user, User);

37

38

// Fluent API for type validation

39

assert("hello").is(assert.string);

40

assert(42).is(assert.string, assert.number); // Multiple type options (OR logic)

41

42

// Complex type validation

43

const UserType = assert.define('User', function(value) {

44

assert(value).is(assert.structure({

45

name: assert.string,

46

age: assert.number

47

}));

48

});

49

50

const users = [

51

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

52

{ name: "Bob", age: 30 }

53

];

54

55

assert.type(users, assert.arrayOf(UserType));

56

```

57

58

## Architecture

59

60

rtts_assert is built around several core concepts:

61

62

- **Type Assertion Engine**: Core validation logic using `instanceof` checks and custom assertion methods

63

- **Fluent API**: `assert(value).is(...types)` pattern for flexible type checking

64

- **Custom Type System**: `assert.define()` for creating reusable type definitions with validation logic

65

- **Traceur Integration**: Native support for Traceur type annotations and runtime type checks

66

- **Error Reporting**: Detailed error messages with validation context and nested error structures

67

68

## Capabilities

69

70

### Core Type Assertion

71

72

Fundamental type checking functions that validate values against expected types.

73

74

```javascript { .api }

75

/**

76

* Asserts that a value is of the specified type, throws error if not

77

* @param actual - Value to check

78

* @param T - Type constructor or type definition

79

* @throws Error with detailed message if type check fails

80

*/

81

assert.type(actual, T);

82

83

/**

84

* Validates function arguments in pairs (value, type, value, type, ...)

85

* @param ...params - Alternating values and types

86

* @throws Error with position-specific messages for invalid arguments

87

*/

88

assert.argumentTypes(...params);

89

90

/**

91

* Validates return value type and returns the value if valid

92

* @param actual - Return value to validate

93

* @param T - Expected return type

94

* @returns The validated value

95

* @throws Error if return type is invalid

96

*/

97

assert.returnType(actual, T);

98

```

99

100

### Fluent Type Validation

101

102

Flexible type checking using a fluent API pattern.

103

104

```javascript { .api }

105

/**

106

* Creates a fluent validation object for the given value

107

* @param value - Value to validate

108

* @returns Object with 'is' method for type checking

109

*/

110

assert(value);

111

112

/**

113

* Fluent validation interface

114

*/

115

interface FluentValidator {

116

/**

117

* Validates value against one or more types (OR logic)

118

* @param ...types - Variable number of type constructors

119

* @returns true if value matches any type, false otherwise

120

*/

121

is(...types): boolean;

122

}

123

```

124

125

**Usage Example:**

126

127

```javascript

128

// Single type check

129

const isValid = assert("hello").is(assert.string);

130

131

// Multiple type options (OR logic)

132

const isValidNumber = assert(42).is(assert.string, assert.number);

133

134

// Complex validation in custom types

135

const MyType = assert.define('MyType', function(value) {

136

return assert(value).is(Object);

137

});

138

```

139

140

### Custom Type Definitions

141

142

System for creating reusable type definitions with custom validation logic.

143

144

```javascript { .api }

145

/**

146

* Creates custom type definitions with validation logic

147

* @param classOrName - Existing class constructor or string name for new interface

148

* @param check - Function containing validation logic

149

* @returns Type constructor with attached 'assert' method

150

*/

151

assert.define(classOrName, check);

152

153

/**

154

* Adds error message to current validation stack

155

* @param message - Error message string

156

*/

157

assert.fail(message);

158

```

159

160

**Usage Examples:**

161

162

```javascript

163

// Define interface from string name

164

const Email = assert.define('Email', function(value) {

165

assert(value).is(assert.string);

166

if (value.indexOf('@') === -1) {

167

assert.fail('must contain "@" symbol');

168

}

169

});

170

171

// Add assertion to existing class

172

class User {}

173

assert.define(User, function(value) {

174

assert(value).is(Function, Object);

175

});

176

177

// Use custom types

178

assert.type("user@example.com", Email);

179

assert.type(new User(), User);

180

```

181

182

### Predefined Type Validators

183

184

Built-in validators for common primitive types.

185

186

```javascript { .api }

187

/**

188

* String type validator using typeof check

189

*/

190

assert.string;

191

192

/**

193

* Number type validator using typeof check

194

*/

195

assert.number;

196

197

/**

198

* Boolean type validator using typeof check

199

*/

200

assert.boolean;

201

```

202

203

### Complex Type Constructors

204

205

Validators for arrays and structured objects with specific type requirements.

206

207

```javascript { .api }

208

/**

209

* Creates validator for arrays containing items of specified types

210

* @param ...types - Variable number of type constructors

211

* @returns Type constructor for array validation

212

*/

213

assert.arrayOf(...types);

214

215

/**

216

* Creates validator for objects with specific property types

217

* @param definition - Object mapping property names to type constructors

218

* @returns Type constructor for object structure validation

219

*/

220

assert.structure(definition);

221

```

222

223

**Usage Examples:**

224

225

```javascript

226

// Array validation

227

const StringOrNumberArray = assert.arrayOf(assert.string, assert.number);

228

assert.type(["hello", 42, "world"], StringOrNumberArray);

229

230

// Object structure validation

231

const UserStructure = assert.structure({

232

name: assert.string,

233

age: assert.number,

234

active: assert.boolean

235

});

236

assert.type({ name: "Alice", age: 25, active: true }, UserStructure);

237

238

// Nested structure validation

239

const ContactStructure = assert.structure({

240

user: UserStructure,

241

emails: assert.arrayOf(assert.string)

242

});

243

```

244

245

## Integration with Traceur

246

247

rtts_assert integrates seamlessly with Traceur's type annotation system for automatic runtime type checking:

248

249

```javascript

250

// Function with type annotations

251

function greet(name: string): string {

252

return `Hello, ${name}!`;

253

}

254

255

// Variable type annotations

256

var count: number = 42;

257

var users: User[] = [];

258

259

// Void return type

260

function logMessage(msg: string): void {

261

console.log(msg);

262

}

263

```

264

265

When compiled with Traceur using `--types=true --type-assertions=true --type-assertion-module="path/to/assert"`, these annotations automatically generate calls to `assert.argumentTypes()`, `assert.returnType()`, and `assert.type()`.

266

267

**Traceur Primitive Types:**

268

269

rtts-assert integrates directly with Traceur's runtime type system through `$traceurRuntime.type`:

270

271

- `$traceurRuntime.type.string` - String type (checked with `typeof value === 'string'`)

272

- `$traceurRuntime.type.number` - Number type (checked with `typeof value === 'number'`)

273

- `$traceurRuntime.type.boolean` - Boolean type (checked with `typeof value === 'boolean'`)

274

- `$traceurRuntime.type.void` - Void/undefined type (checked with `typeof value === 'undefined'`)

275

- `$traceurRuntime.type.any` - Any type (always passes validation)

276

277

These primitive types are used internally by rtts-assert and automatically by Traceur-generated code.

278

279

## Error Handling

280

281

rtts_assert provides detailed error messages with validation context:

282

283

```javascript

284

// Basic error

285

assert.type(123, assert.string);

286

// Error: Expected an instance of string, got 123!

287

288

// Nested validation errors

289

const UserType = assert.define('User', function(value) {

290

assert(value).is(assert.structure({

291

name: assert.string,

292

contact: assert.structure({

293

email: assert.string

294

})

295

}));

296

});

297

298

assert.type({ name: "Alice", contact: { email: 123 } }, UserType);

299

// Error: Expected an instance of User, got {...}!

300

// - {...} is not instance of object with properties name, contact

301

// - 123 is not instance of string

302

303

// Argument validation errors

304

function process(data: string, count: number) {

305

// Generated by Traceur: assert.argumentTypes(data, assert.string, count, assert.number);

306

}

307

308

process(123, "invalid");

309

// Error: Invalid arguments given!

310

// - 1st argument has to be an instance of string, got 123

311

// - 2nd argument has to be an instance of number, got "invalid"

312

```

313

314

## Types

315

316

```javascript { .api }

317

/**

318

* Core assert function interface

319

*/

320

interface Assert {

321

(value: any): FluentValidator;

322

type(actual: any, T: any): void;

323

argumentTypes(...params: any[]): void;

324

returnType(actual: any, T: any): any;

325

define(classOrName: any, check: Function): any;

326

fail(message: string): void;

327

string: TypeValidator;

328

number: TypeValidator;

329

boolean: TypeValidator;

330

arrayOf(...types: any[]): TypeValidator;

331

structure(definition: {[key: string]: any}): TypeValidator;

332

}

333

334

/**

335

* Fluent validation interface

336

*/

337

interface FluentValidator {

338

is(...types: any[]): boolean;

339

}

340

341

/**

342

* Type validator with assert method

343

*/

344

interface TypeValidator {

345

assert(value: any): boolean | void;

346

__assertName?: string;

347

}

348

```