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.ts so callers can share it:
export function doubleSpacing(points: int): int {
return points + points
}A Kotlin or Java caller sees the native signature on the generated module class. In Java, the call is SpacingTs.doubleSpacing(6) and the result is the primitive int value 12. The Swift export uses Int32 for both the parameter and result.
For asynchronous JVM APIs, TypeScript Promise<T> maps to javascript.lang.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.ts 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.