SurrealDB
SurrealDB Docs Logo

Enter a search query

Navigation

Data Types

The JavaScript SDK provides custom classes for SurrealDB-specific data types, ensuring type safety and data integrity when working with the database.

Type Mapping

Primitive Types

These SurrealQL types map directly to JavaScript primitives:

SurrealQL TypeJavaScript TypeExample
boolbooleantrue, false
int, floatnumber42, 3.14
stringstring”hello”
nullnullnull
noneundefinedundefined

Complex Types

These SurrealQL types map to JavaScript complex types:

SurrealQL TypeJavaScript TypeExample
arrayArray[1, 2, 3]
objectObject{ key: "value" }
setSetnew Set([1, 2, 3])

Custom Data Type Classes

These SurrealQL types require custom classes for proper representation:

SurrealQL TypeJavaScript ClassDescription
recordRecordIdType-safe record identifiers
datetimeDateTimeDatetime with nanosecond precision
durationDurationTime duration values
decimalDecimalArbitrary precision decimals
uuidUuidUniversally unique identifiers
geometryGeometry*Geometric/spatial data types
futureFutureDeferred computation values
bytesUint8ArrayBinary data

Utility Types

Additional types for working with queries and ranges:

ClassPurposeDocumentation
TableType-safe table referencesView docs →
RecordIdRangeRange of record IDsView docs →
RangeGeneric range valuesView docs →

Custom Data Type Classes

Core Types

  • RecordId - Type-safe record identifiers with table and ID components

    • new RecordId(table, id) - Create record ID
    • RecordId.parse(string) - Parse from string
    • Also includes RecordIdRange for querying ranges
  • DateTime - Datetime values with nanosecond precision

    • DateTime.now() - Current datetime
    • DateTime.parse(string) - Parse from ISO string
    • .toDate() - Convert to JavaScript Date
  • Duration - Time duration with support for multiple units

    • Duration.parse('5h30m') - Parse from string
    • .toMilliseconds() - Convert to milliseconds
  • Decimal - Arbitrary precision decimal numbers

    • new Decimal('19.99') - Create precise decimal
    • Preserves precision during operations
  • Uuid - Universally unique identifiers

    • Uuid.v4() - Generate random UUID
    • Uuid.v7() - Generate time-ordered UUID
  • Table - Type-safe table references

    • new Table<T>(name) - Create typed table reference
    • Used in SELECT, CREATE, UPDATE, DELETE operations

Geometric Types

  • Geometry - Spatial/geometric data types
    • GeometryPoint - Single point
    • GeometryLine - Line between points
    • GeometryPolygon - Polygon shape
    • GeometryMultiPoint, GeometryMultiLine, GeometryMultiPolygon
    • GeometryCollection - Mixed geometry collection

Advanced Types

  • Future - Deferred computation values for schema definitions

  • Range - Generic range values for numeric and date ranges

Quick Examples

Using Custom Types

import { RecordId, DateTime, Duration, Decimal, Uuid, Table } from 'surrealdb'; // Record identifiers const userId = new RecordId('users', 'john'); const user = await db.select(userId); // Datetime with precision const event = await db.create(new Table('events')).content({ name: 'Meeting', timestamp: DateTime.now(), duration: Duration.parse('1h30m') }); // Precise decimals const product = await db.create(new Table('products')).content({ name: 'Widget', price: new Decimal('19.99') }); // UUID generation const sessionId = Uuid.v7(); // Time-ordered const randomId = Uuid.v4(); // Random

Type Conversion

// DateTime conversions const datetime = DateTime.now(); const jsDate = datetime.toDate(); const isoString = datetime.toString(); // Duration conversions const duration = Duration.parse('5h30m'); const milliseconds = duration.toMilliseconds(); const seconds = duration.toSeconds(); // Decimal conversions const decimal = new Decimal('123.456'); const number = decimal.toNumber(); // May lose precision const string = decimal.toString(); // Preserves precision

Parsing from Strings

// Parse various types const recordId = RecordId.parse('users:john'); const datetime = DateTime.parse('2024-01-15T12:00:00Z'); const duration = Duration.parse('1h30m45s'); const uuid = Uuid.parse('550e8400-e29b-41d4-a716-446655440000');

Type Safety Benefits

Using custom type classes provides several advantages:

  1. Type Safety - TypeScript can validate types at compile time
  2. Precision - Maintains database precision (e.g., nanoseconds, arbitrary decimals)
  3. Validation - Constructors validate input format
  4. Convenience - Helper methods for common operations
  5. Interoperability - Seamless conversion to/from JavaScript types

Best Practices

1. Use Type Parameters

// Good: Type-safe const users = new Table<User>('users'); const results: User[] = await db.select(users); // Good: Explicit ID type const userId = new RecordId<'users', string>('users', 'john');

2. Prefer Classes Over Strings

// Good: Type-safe await db.select(new RecordId('users', 'john')); // Avoid: String-based await db.query('SELECT * FROM users:john');

3. Handle Precision Carefully

// Good: Preserve precision const price = new Decimal('19.99'); const display = price.toString(); // Caution: May lose precision const number = price.toNumber();

4. Validate Parsed Input

try { const uuid = Uuid.parse(userInput); } catch (error) { console.error('Invalid UUID format'); }

See Also