Skip to main content

JS types

Usage information about the core types in JS interop.

Dart values and JS values belong to separate language domains. When compiling to Wasm, they execute in separate runtimes as well. Treat JS values as foreign types. To provide Dart types for JS values, the dart:js_interop library exposes a set of types prefixed with JS called JS types. These types distinguish between Dart values and JS values at compile time.

The compiler represents these types differently based on whether you compile to Wasm or JS. Because of this difference, their runtime types differ, so you can't use is checks or as casts. To interact with and examine JS values, use external interop members or conversions.

Type hierarchy

#

JS types form a natural type hierarchy:

  • Top type: JSAny, which is any non-nullish JS value
    • Primitives: JSNumber, JSBoolean, JSString, JSSymbol, JSBigInt
    • JSObject, which is any JS object
      • JSFunction
        • JSExportedDartFunction, which represents a Dart callback that was converted to a JS function
      • JSArray
      • JSPromise
      • JSDataView
      • JSTypedArray
        • JS typed arrays like JSUint8Array
      • JSBoxedDartObject, which boxes Dart values so you can pass them opaquely within the same Dart runtime
    • JSIterable and JSIterator

The ExternalDartReference type in the dart:js_interop library also passes Dart values opaquely, but it isn't a JS type. To compare the two options, refer to the JSBoxedDartObject versus ExternalDartReference section on this page.

You can find the definition of each type and its built-in helpers in the dart:js_interop API documentation. These helpers include JSPromise.resolve, JSPromise.reject, JSArray.fromAsync, JSFunction.length, JSFunction.name, and static getters for well-known JSSymbol values.

Conversions

#

To use a value from one domain in the other, convert it to the corresponding type. For example, to pass a Dart List<String> to a JS interop API that expects a JS array of strings, convert the list to the JSArray<JSString> type.

Members that convert values from Dart to JS usually start with toJS, and members that convert values from JS to Dart usually start with toDart:

dart
// Dart to JS
JSString jsStr = 'hello world'.toJS;
JSArray<JSString> jsArr = ['a', 'b'].toJS;
​
// JS to Dart
String dartStr = jsStr.toDart;
List<String> dartList = jsArr.toDartStringList;
JSAny? resolved = await jsPromise.toDart;
for (final item in jsIterable.toDartIterable) { /* ... */ }

Not all JS types have a conversion, and not all Dart types have a conversion. The following tables list the supported conversions between dart:js_interop types and Dart types.

Primitives, functions, futures, and references

#
dart:js_interop typeDart typeDart to JSJS to Dart
JSNumber num, int, double toJS toDartDouble, toDartInt
JSBoolean, JSString bool, String toJS toDart
JSExportedDartFunction Function toJS , toJSCaptureThis , toJSVarArgs , toJSCaptureThisVarArgs toDart
JSPromise<T extends JSAny?> Future<T extends JSAny?> toJS toDart
JSAny? (JSPromise or value) FutureOr<T extends JSAny?> ( FutureOr<JSAny?> from toDartFutureOr ) toJSPromiseOrValue toDartFutureOr
JSBoxedDartObject Opaque Dart Object toJSBox toDart
ExternalDartReference Opaque Dart Object? toExternalReference toDartObject

Collections and typed data

#
dart:js_interop typeDart typeDart to JSJS to Dart
JSArray<T extends JSAny?> List<T extends JSAny?> toJS toDart
JSArray<JSNumber?> , JSArray<JSBoolean?> , JSArray<JSString?> List of num? , int? , double? , bool? , or String? (and non-nullable) toJS toDartDoubleList , toDartIntList , toDartBoolList , toDartStringList
JSIterable<T extends JSAny?> Iterable<T extends JSAny?> (lazy, without copying) toJSIterable toDartIterable
JSIterator<T extends JSAny?> Iterator<T extends JSAny?> (lazy, without copying) toJSIterator toDartIterator
Typed arrays like JSUint8Array Typed lists from dart:typed_data toJS toDart

When you convert Function or Future values, keep the following behaviors in mind:

  • Use the Function.toJS getter for fixed-arity callbacks, or the toJSVarArgs getter for variadic callbacks that receive all arguments in a JSArray. Use the Function.toJSCaptureThis or toJSCaptureThisVarArgs getters to pass JavaScript's this value as the callback's first parameter.
  • When a Future converted with the toJS or toJSPromiseOrValue getters fails, JSAny errors reject the JSPromise directly, while other Dart errors reject with a JS Error containing error (of type JSBoxedDartObject) and stack properties.

Requirements on external declarations and Function.toJS

#

To ensure type safety, the compiler restricts which types can flow into and out of JS. Parameter and return types in external declarations must be one of the following:

  • A JS type from dart:js_interop (such as JSString or JSArray) or a custom interop extension type.
  • An ExternalDartReference value.
  • A Dart primitive (bool, num, int, double, String, or void), which the compiler implicitly converts.
good dart
extension type InteropType(JSObject _) implements JSObject {}
​
@JS()
external void primitives(String a, int b, double c, num d, bool e);
​
@JS()
external JSArray jsTypes(JSObject a, JSString b);
​
@JS()
external InteropType get interopType;
​
@JS()
external void externalReference(ExternalDartReference ref);

Arbitrary Dart types like Function or List aren't allowed directly in external declarations and cause a compile-time error:

bad dart
@JS()
external Function get function;
​
@JS()
external set list(List value);

The same type restrictions apply to parameters and return values of Dart callbacks converted with the Function.toJS or Function.toJSCaptureThis getters. Callbacks without optional positional parameters that you convert with the toJS or toJSCaptureThis getters can also be async and return Future<T>, where T is void or a subtype of JSAny?. In contrast, the toJSVarArgs (R Function(JSArray<E>)) and toJSCaptureThisVarArgs (R Function(T, JSArray<E>)) getters require R and E to be subtypes of JSAny? and T to be a subtype of JSObject.

Compatibility, type checks, and casts

#

Because JS interop types are extension types that erase to a single runtime representation (externref) on WebAssembly, standard Dart is checks and as casts can't distinguish between JS types at runtime and might silently succeed on the wrong type.

Avoid is checks and as casts involving interop types:

bad dart
void f(JSAny a, JSString s) {
  if (a is String) { /* ... */ }
  if (a is JSObject) { /* ... */ }
  var str = s as String;
}

Instead, use the isA helper method to check whether a JS value matches a specific JS type or custom interop type:

good dart
void f(JSAny a) {
  if (a.isA<JSString>()) {} // Checks `typeof a === 'string'`
  if (a.isA<JSArray>()) {} // Checks `Array.isArray(a) || a instanceof Array`
  if (a.isA<CustomInteropType>()) {} // Checks `a instanceof CustomInteropType`
}

You can also inspect the underlying JS value with the typeofEquals or instanceOfString methods before casting between interop types:

good dart
void f(JSAny a) {
  if (a.typeofEquals('function')) {
    var fn = a as JSFunction;
  }
}

To catch invalid type checks and casts with JS interop types, enable the invalid_runtime_check_with_js_interop_types lint rule. Starting in package:lints 7.0.0, package:lints/core.yaml includes this rule.

null versus undefined

#

JavaScript has both null and undefined, whereas Dart has only null. When an interop member returns either JS null or undefined, the compiler maps the result to Dart null:

dart
@JS()
external JSObject? get value; // Can return a JSObject, JS null, or undefined.

If a non-nullable interop member returns JS null or undefined, the program throws a runtime error.

JSBoxedDartObject versus ExternalDartReference

#

Both the JSBoxedDartObject and ExternalDartReference types pass opaque references to Dart Object instances through JavaScript:

TypeRepresentationWhen to use
ExternalDartReference ( toExternalReference / toDartObject ) Direct opaque reference (not a subtype of JSAny ; supports nullable Object? ) Default choice for performance when passing a Dart object to and from JS.
JSBoxedDartObject ( toJSBox / toDart ) Wrapped in a JS object (subtype of JSObject and JSAny) When an API requires a JSAny subtype (such as storing in a JSArray ) or when you need runtime checks preventing access across different Dart runtimes.