Skip to Content
Language reference

Modules and native interop

Export typed functions, call the host SDK, and share a module across targets.

Use relative imports between TypeScript modules. Bare package names select package exports at build time. Compiling an installed JavaScript dependency preserves its runtime operations, including property access and callback invocation. The application executes the resulting native code.

Exporting a function

Put the calculation in spacing.tsn so callers can share it:

export function doubleSpacing(points: int): int {
  return points + points
}

Kotlin, Java, and Swift all call SpacingTs.doubleSpacing(6) and get 12. The parameter and result are primitive int on the JVM and Int32 in Swift. A nested file such as ui/spacing.tsn uses ui_SpacingTs in all three languages.

For asynchronous JVM APIs, TypeScript Promise<T> maps to typescriptnative.Promise<T>. Java and Kotlin callers can receive the same promise from an exported function or return one for TypeScript to await. A TypeScript return type of Promise<void> appears as Promise<Void> in Java.

Importing platform types

On Android, import a class from its Java package and call it with its native argument types:

import { TextView } from "android.widget"

export function setHeading(label: TextView, heading: string): void {
  label.setText(heading)
}

The JVM backend produces Java source. Desktop builds compile it into class files. Android converts the bytecode to DEX for ART. An imported Java or Kotlin call uses the overload selected by its argument types.

The Apple backend produces Swift source in the application's module. Import a Swift module when a declaration belongs to a platform framework. A failable initializer returns a nullable value in TypeScript:

import UIKit from "UIKit"

export function loadImage(path: string): UIKit.UIImage | null {
  return UIKit.UIImage.init({ contentsOfFile: path })
}

Keep SDK imports in platform-specific files. Both hosts can import the same spacing.tsn without making that module depend on either Android or UIKit.

Errors

Native errors are errors in TypeScript. A value is an Error when it is a JavaScript error object or a catchable native error of the platform: a java.lang.Throwable on the JVM and a Swift.Error on Apple platforms. A catch receives both. Every Error has the portable members message, name and stack. A native error keeps its concrete type and identity when TypeScript rethrows it to native code.

export function attempt(work: () => void): string {
  try { work(); return "ok" } catch (e) {
    if (e instanceof Error) return e.name + ": " + e.message
    throw e
  }
}

A thrown value that is not an error, such as a string, null, a plain object or a thenable, is caught as itself and fails instanceof Error. Traps and process termination are not errors and cannot be caught.

On this page