Skip to main content

Native Bindings

Communicating between native and JS​

Valdi is designed with a clear performance motto: "What is the highest level API we can expose that's easy and safe to use while allowing us to achieve a high level of performance?"

To achieve this, Valdi uses a unified data container called Valdi::Value in C++ to represent data as it crosses the bridge between TypeScript, Objective-C, and Java. This minimizes the overhead of data conversion and enables features like interned strings and styles.

There are two main ways you can communicate between native and JS.

Choose which one to use based on your use case.

For interaction between your view's TypeScript and native code, the Context object will probably be the best solution for you.

Using the annotations API, the Valdi compiler can generate strongly typed native interfaces/classes which do the conversions in and out between TypeScript and native code.

This is an example of an interaction between both platforms with them:

You can call native logic from TypeScript valdi code:

/**
* @Context
* @ExportModel({
* ios: 'SCYourComponentContext',
* android: 'com.snap.myfeature.YourComponentContext'
* })
*/
interface YourComponentContext {
callMeFromTS?();
}
/**
* @Component
* [...]
*/
class YourComponent extends Component<YourComponentViewModel, YourComponentContext> {
onMyButtonWasTapped() {
// Calls callMeFromTS: on the SCYourComponentContext (if it has been configured)
this.context.callMeFromTS?.();
}
}

This is what the generated Obj-C counterpart looks like:

@interface SCYourComponentContext: SCValdiMarshallableObject

@property (copy, nonatomic) SCYourComponentContextOnDoneBlock _Nullable callMeFromTS;

- (instancetype _Nonnull)init;

// ...

@end

//////////

// So you can instantiate SCYourComponentContext and configure it with the callMeFromTS block:
SCYourComponentContext *componentContext = [[SCYourComponentContext alloc] init];
componentContext.callMeFromTS = ^{
// Will be called when this.context.callMeFromTS() is called in TS.
NSLog(@"Hello from Objective-C");
}

and Kotlin:

package com.snap.myfeature.YourComponentContext

class SCYourComponentContextImpl {
val onDone: (() -> Unit)?
// ...
}

//////////

// So you can instantiate YourComponentContext and configure it with the callMeFromTS block:
val componentContext = YourComponentContext()
componentContext.callMeFromTS = {
// Will be called when this.context.callMeFromTS() is called in TS.
print("Hello from Kotlin")
}

You can also pass callbacks from JS to native:

TypeScript:

interface YourComponentContext {
callMeFromTS?(completion: (arg: string) => void);
}
class YourComponent extends Component<any, YourComponentContext> {
onMyButtonWasTapped() {
this.context.callMeFromTS((arg) => {
console.log('the native code called the completion function with arg:', arg);
});
}
}

Objective-C:

componentContext.callMeFromTSWithCompletion = ^(YourComponentContextCallMeFromTSCompletionBlock completion) {
// This will call the TS callback and provide the given value.
completion(@"I got you loud and clear");
}

Kotlin:

componentContext.callMeFromTSWithCompletion = { completion ->
// This will call the TS callback and provide the given value.
completion(@"I got you loud and clear");
}

This will print 'the native code called the completion function with arg: I got you loud and clear'.

ExportFunction​

If you need to use TypeScript code outside of a Valdi component, you can use the @ExportFunction annotation:

// @ExportFunction({ios: 'SCMultiplier', android: 'com.valdi.example.Multiplier'})
export function multiply(left: number, right: number): number {
return left * right;
}

This will generate Objective-C/Swift/Kotlin files which can call this function, and will handle parameter serialization/deserialization automatically:

#import <ModuleName/SCMultiplier.h>

- (void)viewDidLoad
{
/// inject the id<SCValdiRuntimeProtocol> dependency
[valdiRuntime getJSRuntimeWithBlock:^(id<SCValdiJSRuntime> runtime) {
double result = SCMultiplierMultiply(runtime, 2, 4);
NSLog(@"Result is: %fs", result);
}];
}
@Inject lateinit var runtime: IValdiRuntime

fun onCreate() {
runtime.createScopedJSRuntime {
val result = Multiplier.multiply(it, 2, 4)
println("Result is: ${result}")
}
}

This API supports the whole range of the Valdi annotations. As such it can be used to pass in/return complex objects:

// @ExportModel({ios: 'SCValdiUser', android: 'com.valdi.example.User'})
interface User {
name: string;
}

// @ExportModel({ios: 'SCValdiSearchEngine', android: 'com.valdi.example.SearchEngine'})
interface SearchEngine {
search(term: string, completion: (results: User[]) => void);
}

// @ExportFunction({ios: 'SCValdiSearchEngineFactory', android: 'com.valdi.example.SearchEngineFactory'})
export function makeSearchEngine(users: User[]): SearchEngine {
// Note: in a near future, you will be able to make the class itself
// implements the interface and return it.
const engine = new ConcreteSearchEngine(users);

return {
search(term: string, completion: (results: User[]) => void) {
const results = engine.performSearch(term);
completion(results);
}
};
}

iOS:

- (void)viewDidLoad
{
[UIView.valdiRuntime getJSRuntimeWithBlock:^(id<SCValdiJSRuntime> runtime) {
NSArray<SCValdiUser *> *allUsers = fetchAllUsers();
SCValdiSearchEngine *searchEngine = SCValdiSearchEngineFactoryMakeSearchEngine(runtime, allUsers);
self.searchEngine = searchEngine;
}];
}

// Later on...
- (void)updateUsers
{
[self.searchEngine searchWithTerm:@"Simon" withCompletion:^(NSArray<SCValdiUser *> *results) {
NSLog(@"Found those users: %@", results);
}];
}

Android:

@Inject lateinit var runtime: IValdiRuntime
var searchEngine: SearchEngine? = null

fun onCreate() {
runtime.createScopedJSRuntime {
val allUsers = fetchAllUsers()
val searchEngine = SearchEngineFactory.makeSearchEngine(it, allUsers)
this.searchEngine = searchEngine
}
}

// Later on...
fun updateUsers() {
searchEngine?.search("Simon") {
println("Found those users: ${it}")
}
}

Note that calling a JS function will automatically asynchronously dispatch to the JS thread if needed. If your function need to return a value synchronously to platform code, make sure you call this function within a createScopedJSRuntime scope. If you use asynchronous completion functions this will never be a problem.

Using a Polyglot Module​

If you want to be able to write a reuseable module using a separate language like Kotlin, Java, Objective-C, C++ or Swift, with an exposed TS API, you can make a polyglot module. See documentation about polyglot modules for more details.


Type System Reference​

This section documents all TypeScript types that can be marshalled between TypeScript and native code.

Supported Primitive Types​

TypeScript TypeiOS (Obj-C)iOS (Swift)Android (Kotlin)C++Notes
stringNSString *StringStringstd::stringUTF-8 encoded
numberdoubleDoubleDoubledouble64-bit floating point
booleanBOOLBoolBooleanbool
voidvoidVoidUnitvoidFor return types
anyidAnyAnyValueDynamic/untyped value
objectidAnyAnyValueUntyped object

Supported Complex Types​

TypeScript TypeNative EquivalentNotes
T[]Array/NSArray/ListArrays of any supported type
Promise<T>Async operationMapped to platform async patterns
CancelablePromise<T>Cancelable asyncExtended Promise with cancellation
Map<string, any>Dictionary/MapCurrently only supports string keys and any values
(arg: T) => RBlock/Closure/LambdaFunction/callback types
T | null | undefinedOptional/nullableNullable types
T?Optional/nullableTypeScript optional syntax

Special Types​

TypeScript TypePurposeNative Equivalent
Uint8ArrayBinary dataData (iOS) / ByteArray (Android)
Long64-bit integersint64_t / Long
bigintArbitrary precision integersSCValdiBigInt / com.snap.valdi.BigInt
NumberExplicit doubleSame as number but explicit

On Apple platforms, bigint bindings with JavaScriptCore require iOS 18 or later or macOS 15 or later.

Generated Types​

Types defined with annotations can be passed between TypeScript and native:

  • @ExportModel interfaces/classes → Generated native classes
  • @ExportProxy interfaces → Native must implement
  • @ExportEnum enums → Generated native enums

Example:

// @ExportModel({ios: 'SCUser', android: 'com.example.User'})
interface User {
name: string;
age: number;
friends?: User[]; // Optional array of User
}

Generic Types​

Generics are supported on generated types:

// @ExportModel({ios: 'SCContainer', android: 'com.example.Container'})
interface Container<T> {
value: T;
}

// Usage
interface MyContext {
userContainer: Container<User>;
stringContainer: Container<string>;
}

Generics only work on types annotated with @ExportModel. Generic parameters must be resolved to concrete types at the interface boundary.


Type Limitations and Constraints​

Union Types​

✅ SUPPORTED: Union with null/undefined

property: string | null;
property: string | undefined;
property?: string; // Equivalent to: string | undefined

❌ NOT SUPPORTED: Other union types

property: string | number;  // ERROR: Only null/undefined unions supported
property: 'red' | 'blue' | 'green'; // ERROR: Use enum instead

Solution: Use enums for multiple value choices:

// @ExportEnum({ios: 'Color', android: 'com.example.Color'})
enum Color {
Red = 'red',
Blue = 'blue',
Green = 'green'
}

interface Config {
color: Color; // ✅ Works
}

Map Type Limitations​

⚠️ PARTIAL SUPPORT:

// ✅ SUPPORTED: Map with string keys and any values
metadata: Map<string, any>;

// ❌ NOT FULLY SUPPORTED: Typed maps
typedMap: Map<string, User>; // Limited - treated as Map<string, any>

// ❌ NOT SUPPORTED: Non-string keys
numberMap: Map<number, string>; // Not supported

Workaround: Use objects with @ExportModel for typed dictionaries:

// @ExportModel
interface UserMap {
[key: string]: User; // Use index signature
}

Array Nesting​

Arrays can be nested to any depth:

matrix: number[][];  // ✅ 2D array
cube: number[][][]; // ✅ 3D array

Interface Inheritance​

An @ExportModel / @ExportProxy interface can extends another TypeScript interface. Two modes control what shows up in the generated native class.

Flatten mode (default): parent members are merged into the child's native class.

/**
* @ExportModel({ios: 'SCTimestamped', android: 'com.example.Timestamped'})
*/
export interface Timestamped {
createdAt: number;
updatedAt: number;
}

/**
* @ExportModel({ios: 'SCUser', android: 'com.example.User'})
*/
export interface User extends Timestamped {
id: string;
name: string;
}
// Generated native `User` exposes: createdAt, updatedAt, id, name.

The parent must be exported, carry a Valdi annotation (@ExportModel, @ExportProxy, @NativeInterface, etc.), and live in the same module being compiled. Requirements:

  • Annotated: plain export interface Foo with no annotation is filtered out of the TypeScript companion's dump; flatten will fail with a specific error naming the type and file.
  • Same module: each Valdi module is compiled in isolation, so the flattener's parent lookup index only contains files from the current compilation. Cross-module inheritance (e.g. Child extends ParentFromDependency) is a v1 limitation — use ignoreInheritance: 'true' for those cases until cross-module parent resolution lands (tracked separately).
  • No annotated parent members: if any inherited member itself carries a Valdi annotation (@Untyped, @WorkerThread, @Injectable, @ConstructorOmitted, @SingleCall, @AllowSyncCall, @UntypedMap), flatten rejects with a clear error. Those semantics can't be safely re-interpreted against the child's file offsets in v1. Use ignoreInheritance: 'true' or remove the annotation from the parent.

Multi-level chains are walked depth-first — grandparent members come first, then parent, then child. Diamond inheritance (child extends B and C, both extend A) merges A's members exactly once.

TS-only mode (ignoreInheritance: 'true'): parent is used purely for TypeScript typing; the native class emits from the child body only.

/**
* @ExportModel({ignoreInheritance: 'true'})
*/
export interface GenerateThumbnailError extends StepErrorType<GenerateThumbnailErrorCode> {
code: GenerateThumbnailErrorCode;
message?: string;
nonFatal?: boolean;
}
// Generated native class: code, message?, nonFatal?. Parent generics ignored.

Reach for ignoreInheritance: 'true' when the parent is generic (Parent<T>), unannotated, lives in a .d.ts file, or when you want to own the native field list explicitly. The compiler skips all flatten guards in this mode.

❌ NOT SUPPORTED (flatten mode only — use ignoreInheritance if you need any of these):

interface Child extends Parent<T> {}   // Generic parents — v1 limitation.
interface Child implements Foo {} // `implements` clauses.
interface A extends B {} interface B extends A {} // Cycles → compiler error.

Collision policy: If the child re-declares an inherited member name under flatten, the compiler errors by default. The inheritanceCollisionPolicy annotation parameter is reserved for future override modes (childWins, sameTypeOnly); only error is honored today.


Type Conversion Behavior​

Number Precision​

TypeScript number always maps to native double (64-bit floating point):

interface Data {
count: number; // Native: double (not int!)
}

For 64-bit integers:

interface Data {
timestamp: Long; // Use Long type for precise 64-bit integers
}

JavaScript numbers can only precisely represent integers up to 2^53 - 1. For larger integers, use bigint for arbitrary precision, or Long for the existing 64-bit wrapper. bigint bindings with JavaScriptCore require iOS 18+ or macOS 15+.

Array Conversion​

Arrays are copied when crossing the native/TypeScript boundary:

interface DataProcessor {
// Array is copied from native to TS
processData(items: string[]): void;

// Array is copied from TS to native
getData(): string[];
}

Implications:

  • Modifications in one environment don't affect the other
  • Large arrays have serialization overhead
  • Consider using Uint8Array for binary data to reduce overhead

Object Marshalling​

Only objects with annotations can be marshalled:

// ✅ Can be passed - has @ExportModel
// @ExportModel
interface User {
name: string;
}

// ❌ Cannot be passed - plain object
interface Config {
data: { key: string, value: number }; // ERROR
}

Solution: Use any with @Untyped annotation:

interface Config {
// @Untyped
data: any; // Dynamic object, no type safety
}

Or define a proper interface:

// @ExportModel
interface KeyValue {
key: string;
value: number;
}

interface Config {
data: KeyValue; // ✅ Works
}

Callback Lifecycle​

Callbacks are reference-counted:

interface Context {
callback: () => void;
}

Memory Management:

  • Native holds a strong reference to the callback
  • Callback is released when native object is destroyed
  • Use @SingleCall to automatically release after first invocation
interface Context {
// @SingleCall
onComplete: () => void; // Automatically released after first call
}

Performance Considerations​

Thread Safety​

All TypeScript function calls are dispatched to the JavaScript thread:

interface DataFetcher {
// Automatically dispatches to JS thread
fetchData(): Promise<Data>;
}

For synchronous calls:

// iOS: Use scoped runtime
[valdiRuntime getJSRuntimeWithBlock:^(id<SCValdiJSRuntime> runtime) {
// Synchronous calls work here
double result = MyFunction(runtime, arg);
}];
// Android: Use scoped runtime
runtime.createScopedJSRuntime { jsRuntime ->
// Synchronous calls work here
val result = MyFunction.call(jsRuntime, arg)
}

For heavy operations:

interface Processor {
// @WorkerThread
processLargeDataset(data: Uint8Array): Promise<Result>;
}

Data Serialization Overhead​

Each parameter is serialized/deserialized when crossing the boundary:

// ❌ BAD: Many small calls
for (let i = 0; i < 1000; i++) {
context.updateProgress(i); // 1000 boundary crossings!
}

// ✅ GOOD: Batch operations
context.updateProgressBatch(progressArray); // 1 boundary crossing

Callback Overhead​

Minimize chatty APIs:

// ❌ BAD: Callback for each item
interface ItemProcessor {
processItems(items: Item[], onEachItem: (item: Item) => void): void;
}

// ✅ GOOD: Single completion callback
interface ItemProcessor {
processItems(items: Item[]): Promise<Item[]>;
}

Best Practices​

Do's ✅​

  1. Keep interfaces simple - Use primitive types when possible
  2. Use @ExportModel for complex types - Don't rely on any
  3. Document null behavior - Be explicit about optional properties
  4. Use @SingleCall for one-time callbacks - Prevents memory leaks
  5. Batch operations - Reduce boundary crossings
  6. Use Promise for async operations - More ergonomic than callbacks
  7. Use Uint8Array for binary data - More efficient than arrays

Don'ts ❌​

  1. Don't use union types (except with null/undefined)
  2. Don't pass large objects frequently - High serialization cost
  3. Don't assume synchronous execution - Use scoped runtime if needed
  4. Don't hold strong references to callbacks indefinitely
  5. Don't pass plain JavaScript objects - Use @ExportModel instead
  6. Don't use Map with non-string keys

Common Patterns​

Async Operations:

interface DataFetcher {
// ✅ PREFERRED: Promise-based
fetchData(): Promise<Data>;
}

Bidirectional Communication:

interface Chat {
sendMessage(text: string): void;

// Native → TS callbacks
onMessageReceived?: (text: string) => void;
onError?: (error: string) => void;
}

Resource Management:

interface FileReader {
open(path: string): void;
read(): Uint8Array;
close(): void; // Important: Always provide cleanup
}

See Also​

Was this page helpful?
Yes
No