Skip to main content

Custom Enums (A | B)

There's two different types of enums - enums and unions.

TypeScript enums​

A TypeScript enum is essentially just an object where each key is backed by ascending integer values. Nitrogen will generate a C++ enum natively, which bridges to JS as a simple integer:

import { type HybridObject, Apple } from 'nitro-core'

enum Gender {
MALE,
FEMALE
}
@Apple(...)
export declare class Person extends HybridObject {
getGender(): Gender
}

This is efficient because MALE is the number 0, FEMALE is the number 1, and all other values are invalid.

TypeScript union​

A TypeScript union is essentially just a variant of literal strings, which is only "typed" via TypeScript.

import { type HybridObject, Apple } from 'nitro-core'

type Gender = 'male' | 'female'
@Apple(...)
export declare class Person extends HybridObject {
getGender(): Gender
}

Nitrogen statically generates hashes for the strings "male" and "female" at compile-time, allowing for very efficient conversions between JS strings and native enums.

String values in Swift and Kotlin​

Generated Swift and Kotlin enums can convert to and from the string each value has in JS. For a union that is the literal ("male"), and for a TypeScript enum it is the member name ("MALE").

let gender = Gender(fromString: "male") // .male, or nil for an unknown string
let string = Gender.male.stringValue // "male"

Swift's description and Kotlin's toString() also return this string. In Kotlin, name still returns the generated entry name (MALE).

Unions need a name​

A TypeScript union consisting of only literal strings needs to be aliased to a separate type so that nitrogen can generate the native enum accordingly.

Bad ❌
import { type HybridObject, Apple } from 'nitro-core'


@Apple(...)
export declare class Person extends HybridObject {
getGender(): 'male' | 'female'
}
Good ✅
import { type HybridObject, Apple } from 'nitro-core'

type Gender = 'male' | 'female'
@Apple(...)
export declare class Person extends HybridObject {
getGender(): Gender
}