Kotlin Standard Library for JavaScript target with comprehensive W3C DOM bindings and JavaScript interoperability features.
—
Core JavaScript interoperability functionality for seamless integration between Kotlin and JavaScript code, including dynamic typing, JSON manipulation, Promise support, and regular expressions.
Execute JavaScript code directly within Kotlin functions.
/**
* Puts the given piece of JavaScript code right into the calling function.
* The compiler replaces call to `js(...)` with the string constant provided as parameter.
* @param code the piece of JavaScript code to put to the generated code. Must be compile-time constant.
*/
external fun js(code: String): dynamicUsage Examples:
// Execute JavaScript Math functions
val max = js("Math.max(1, 2, 3)")
val random = js("Math.random()")
// Access JavaScript objects
val console = js("console")
js("console.log('Hello from Kotlin!')")
// Variable references
fun logMessage(message: String) {
js("console.log(message)") // Can reference Kotlin parameters
}Type checking and conversion utilities for JavaScript interoperability.
/**
* Function corresponding to JavaScript's `typeof` operator
*/
external fun jsTypeOf(a: Any?): String
/**
* Placeholder for external function bodies and default parameters
*/
external val definedExternally: Nothing
/**
* Cast any value to dynamic type
*/
inline fun Any?.asDynamic(): dynamic
/**
* Unsafe type casting - bypasses Kotlin type system
*/
inline fun <T> Any?.unsafeCast(): TUsage Examples:
val obj: Any = "hello"
val type = jsTypeOf(obj) // "string"
val dynamic = obj.asDynamic()
dynamic.length // Access JavaScript properties
val str: String = obj.unsafeCast<String>() // Force type cast
val isUndefined = obj === undefinedType-safe JSON object creation and manipulation.
/**
* JSON object interface with indexing operations
*/
external interface Json {
operator fun get(key: String): Any?
operator fun set(key: String, value: Any?)
}
/**
* Create JSON objects from key-value pairs
*/
fun json(vararg pairs: Pair<String, Any?>): Json
/**
* Add properties from another JSON object
*/
fun Json.add(other: Json): Json
/**
* JavaScript JSON object with global methods
*/
external object JSON {
fun stringify(value: Any?): String
fun stringify(value: Any?, replacer: Array<String>?): String
fun stringify(value: Any?, replacer: ((key: String, value: Any?) -> Any?)?): String
fun parse(text: String): dynamic
fun parse(text: String, reviver: (key: String, value: Any?) -> Any?): dynamic
}Usage Examples:
// Create JSON objects
val person = json(
"name" to "John Doe",
"age" to 30,
"active" to true
)
// Access properties
val name = person["name"]
person["email"] = "john@example.com"
// Merge objects
val address = json("city" to "New York", "zip" to "10001")
val combined = person.add(address)
// JavaScript JSON methods
val jsonString = JSON.stringify(person)
val parsed = JSON.parse(jsonString)JavaScript Promise wrapper with type-safe chaining and error handling.
/**
* JavaScript Promise wrapper
*/
external class Promise<out T> {
constructor(executor: (resolve: (T) -> Unit, reject: (Throwable) -> Unit) -> Unit)
fun <R> then(onFulfilled: ((T) -> R)?): Promise<R>
fun <R> then(onFulfilled: ((T) -> R)?, onRejected: ((Throwable) -> R)?): Promise<R>
fun <R> catch(onRejected: (Throwable) -> R): Promise<R>
fun <R> finally(onFinally: () -> Unit): Promise<T>
companion object {
fun <T> resolve(value: T): Promise<T>
fun <T> reject(reason: Throwable): Promise<T>
fun <T> all(promises: Array<Promise<T>>): Promise<Array<T>>
fun <T> race(promises: Array<Promise<T>>): Promise<T>
}
}Usage Examples:
// Create promises
val promise = Promise<String> { resolve, reject ->
// Async operation
resolve("Success!")
}
// Chain operations
promise
.then { result -> result.uppercase() }
.then { upper -> console.log(upper) }
.catch { error -> console.error("Error: $error") }
// Static methods
val resolved = Promise.resolve("Immediate value")
val rejected = Promise.reject(RuntimeException("Error"))
// Multiple promises
val promises = arrayOf(
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3)
)
Promise.all(promises).then { results ->
console.log("All resolved: ${results.joinToString()}")
}JavaScript RegExp wrapper with pattern matching capabilities.
/**
* JavaScript regular expression
*/
external class RegExp {
constructor(pattern: String)
constructor(pattern: String, flags: String?)
val global: Boolean
val ignoreCase: Boolean
val multiline: Boolean
val source: String
var lastIndex: Int
fun test(string: String): Boolean
fun exec(string: String): RegExpMatch?
}
/**
* Regular expression match result
*/
external interface RegExpMatch {
val index: Int
val input: String
operator fun get(index: Int): String?
val length: Int
}
/**
* Reset regex state (clear lastIndex)
*/
fun RegExp.reset()Usage Examples:
// Create regex patterns
val emailRegex = RegExp("""[\w._%+-]+@[\w.-]+\.[A-Za-z]{2,}""")
val phoneRegex = RegExp("""\d{3}-\d{3}-\d{4}""")
// Test strings
val isEmail = emailRegex.test("user@example.com") // true
val isPhone = phoneRegex.test("123-456-7890") // true
// Extract matches
val pattern = RegExp("""(\d{4})-(\d{2})-(\d{2})""")
val match = pattern.exec("2023-12-25")
if (match != null) {
val year = match[1] // "2023"
val month = match[2] // "12"
val day = match[3] // "25"
}
// Global matching
val globalPattern = RegExp("""\w+""", "g")
globalPattern.reset() // Reset before reuseRead-only interfaces for JavaScript native collection types.
/**
* Read-only JavaScript Array interface
*/
external interface JsReadonlyArray<out E> {
val length: Int
operator fun get(index: Int): E
}
/**
* Read-only JavaScript Set interface
*/
external interface JsReadonlySet<out E> {
val size: Int
fun has(value: E): Boolean
}
/**
* Read-only JavaScript Map interface
*/
external interface JsReadonlyMap<K, out V> {
val size: Int
fun has(key: K): Boolean
fun get(key: K): V?
}Usage Examples:
// Work with JavaScript arrays
val jsArray: JsReadonlyArray<String> = js("['a', 'b', 'c']")
val length = jsArray.length // 3
val first = jsArray[0] // "a"
// Work with JavaScript sets
val jsSet: JsReadonlySet<String> = js("new Set(['x', 'y', 'z'])")
val hasX = jsSet.has("x") // true
val size = jsSet.size // 3
// Work with JavaScript maps
val jsMap: JsReadonlyMap<String, Int> = js("new Map([['a', 1], ['b', 2]])")
val value = jsMap.get("a") // 1
val hasKey = jsMap.has("b") // trueEnable iteration over dynamic JavaScript objects.
/**
* Iterator support for dynamic objects
*/
operator fun dynamic.iterator(): Iterator<dynamic>Usage Examples:
val jsObject = js("{ a: 1, b: 2, c: 3 }")
val jsArray = js("[1, 2, 3, 4, 5]")
// Iterate over JavaScript arrays
for (item in jsArray) {
console.log(item)
}
// Note: Object iteration depends on JavaScript object structure// Core dynamic type
external interface dynamic
// External definition marker
external val definedExternally: Nothing
// JSON object type
external interface Json : dynamic
// Promise type with generic parameter
external class Promise<out T>
// Regular expression types
external class RegExp
external interface RegExpMatch
// JavaScript collection interfaces
external interface JsReadonlyArray<out E>
external interface JsReadonlySet<out E>
external interface JsReadonlyMap<K, out V>Install with Tessl CLI
npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-stdlib-js