Constants provide a typed way for native code to share values with JavaScript. Oskar contrasts stable screen dimensions with a window size that can change, then uses a hard-coded local storage key as the example.
How to Add Type-Safe Constants to Swift TurboModules
Speaker
Oskar from Callstack explains how to expose type-safe constants from a Swift React Native TurboModule.
Oskar defines a LocalStorageConstants type with a storageKey field and returns it from getConstants. Codegen recognizes that exact method name and generates typed interfaces; a similarly shaped getMyConstants method instead returns an untyped NSDictionary.
On the Swift side, Oskar makes storageKey a public static constant so Objective-C can access it. The Objective-C++ implementation stores the value during initialization and uses the generated NativeLocalStorage.storageKey key, which catches misspelled keys at compile time.
The implementation provides both getConstants and constantsToExport because the generated protocol requires both, though Oskar observes that only getConstants is called in his debugging. He also implements getMyConstants with an empty dictionary to satisfy the protocol, noting that it lacks end-to-end type safety.
Oskar verifies that JavaScript retrieves the storage key and that the native getConstants method runs when requested. He points to React Native's Native Device Info spec as an example of caching constants so the native method runs only once, and confirms the value is typed as a string.
Takeaways
- Name the spec method getConstants to activate TurboModule constant codegen and typing.
- Share constant keys through generated types to catch misspellings at compile time.
- Expose Swift values as public static constants when Objective-C needs to read them.
- Implement both generated native methods, even if only getConstants is observed at runtime.
- Cache constants in the JavaScript spec when repeated native lookups are unnecessary.
Mentioned in this talk
Search inside this talk
What was claimed 3
- featureReact Native: Built-in device info TurboModule exposes screen height and width as constants
“the native device info module, which exposes the screen height and width”
YouTube Unverified1 source· Talk
- featurecode generation: Recognizes getConstants and generates typed constants interfaces for TurboModules
“Codegen looks for the getConstants method, then uses a different set of typings and code generation.”
YouTube Unverified1 source· Talk
- featureNativeLocalStorage: Exposes a storageKey constant from native code to JavaScript with end-to-end type safety
“we get full end-to-end type safety”
YouTube Unverified1 source· Talk













