question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Typescript realm types return RealmObject not their original type

See original GitHub issue

Goals

Using Typescript i am attempting to use RealmJS and retrieve some objects after persisting them

Expected Results

when i fetch the results they are of the type i defined them as in this case ‘Party’

Actual Results

they are RealmObject instead of my Party type

Steps to Reproduce

Use the format of the code below

Code Sample

Party type

import { NameBadge } from '../interfaces/NameBadge'
import { WalkInConfig } from '../interfaces/WalkInConfig'
import { Grouping } from '../interfaces/Grouping'
import { Survey } from '../interfaces/Survey'
import { NamecardQuota } from '../interfaces/NameCardQuota'
import { Question } from '../interfaces/Question'
import { Expose } from 'class-transformer'
import getRealm from './realm'

export class Party {
	id!: number
	name!: string
	@Expose({ name: 'start_at' })
	startAt!: Date
	@Expose({ name: 'end_at' })
	endAt!: Date
	place?: string | null
	details?: string | null
	logo!: string
	@Expose({ name: 'logo_bnw' })
	logoBnw!: string
	@Expose({ name: 'name_badge' })
	nameBadge!: NameBadge
	@Expose({ name: 'name_badges' })
	nameBadges!: NameBadge[]
	@Expose({ name: 'attendee_ids' })
	attendeeIds!: number[]
	@Expose({ name: 'grouping_ids' })
	groupingIds!: number[]
	@Expose({ name: 'updated_at' })
	updatedAt!: Date
	@Expose({ name: 'created_at' })
	createdAt!: Date
	@Expose({ name: 'custom_attendee_field_names' })
	customAttendeeFieldNames!: string[]
	@Expose({ name: 'walk_in_config' })
	walkInConfig!: WalkInConfig
	@Expose({ name: 'updated_attendee_ids' })
	updatedAttendeeIds!: number[]
	@Expose({ name: 'attendee_custom_line_1' })
	attendeeCustomLine1?: string | null
	@Expose({ name: 'attendee_custom_line_2' })
	attendeeCustomLine2?: string | null
	questions!: Question[]
	groupings!: Grouping[]
	surveys!: Survey[]
	@Expose({ name: 'namecard_quota' })
	namecardQuota!: NamecardQuota
	static schema: Realm.ObjectSchema

	static parties(): Party[] {
		console.log(getRealm().objectForPrimaryKey(Party.schema.name, 34)) // returns RealmObject rather than 
		return Array.from(getRealm().objects<Party>(Party.schema.name))
	}

	static persist(party: Party) {
		console.log(Party)
		getRealm().write(() => getRealm().create(Party.schema.name, party))
	}

	get stuff() {
		console.log("sup")
		return 'hey there'
	}

	set stuff(val: String) {
		
	}
}

Party.schema = {
	name: 'Party',
	primaryKey: 'id',
	properties: {
		id: 'int',
		name: 'string',
		startAt: 'date',
		endAt: 'date',
		place: 'string?',
		details: 'string?',
		logo: 'string',
		logoBnw: 'string',
		attendeeIds: 'int[]',
		groupingIds: 'int[]',
		updatedAt: 'date',
		createdAt: 'date',
		customAttendeeFieldNames: 'string[]',
		updatedAttendeeIds: 'int[]',
		attendeeCustomLine1: 'string?' ,
		attendeeCustomLine2: 'string?'
	}
}

realm.js file for holding shared instance

import { Party } from './Party'
import { Test } from './test'
import Realm from 'realm'

let realmInstance: Realm | null

const getRealm = (): Realm => {
	if (realmInstance == null) realmInstance = new Realm({ schema: [ Party.schema, Test] })
	return realmInstance!
}

export default getRealm

snippet of me using RealmJS in a component

try {
	let existingParties: Party[] = Party.parties()
	console.log(existingParties)
	if (existingParties.length == 0) {
		let fetchParties = await fetch(path, {
			headers: {
				Authorization: `Bearer ${this.accessToken}`
			}
		})

		let responseJson = await fetchParties.json()
		let parties: Party[] = responseJson.parties.map( (x: any) => plainToClass(Party,x) )
		parties.forEach(x => Party.persist(x))

	} else {
		this.partiesFetcher.next(existingParties.map(x => new Party(x))) // this function expects Party Type but get's RealmObjects and has a hissy fit.
	}
} catch (e) {
	console.log(e)
}

And to confirm the behaviour i wrote a quick ‘Test.js’ class

import Realm, { ObjectSchema } from 'realm'

export class Test {
 
  get stuff()   {
    return "hello"
  }

  set stuff(val) {

  }
}

Test.schema = {
  name: 'Test',
    primaryKey: 'id',
    properties: {
      id: 'int',
      name: 'string'
    }
}

snippet attempting to retrieve Test type

let object = getRealm().objectForPrimaryKey('Test',123)
console.log(object)
if (object == null){
	getRealm().write(() => {
		getRealm().create(Test.schema.name, {id: 123, name: "steve"})
	})
}

This prints a Test type in the console and further more has the stuff method, the Party or RealmObject does not contain the defined methods.

Here is an repo project detailing what i am referring to

Version of Realm and Tooling

  • Realm JS SDK Version: “^2.26.1”
  • Node or React Native: “0.59.4”
  • Client OS & Version: Mojave 10.14.5
  • Which debugger for React Native: ? React Native Debugger

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:1
  • Comments:11 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
knethcommented, Aug 19, 2019

When I run your app, I get:

[ { id: 4, name: 'abc' } ]
[ { id: 1, name: 'a' }, { id: 2, name: 'b' } ]

I agree that we should take a closer look at our TypeScript support and improve it.

1reaction
knethcommented, Sep 15, 2021

@utkarsh-bandekar We are working on a project to revisit how classes can be used for data modelling but I can’t promise a release date.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Realm Object relationships using typescript - Stack Overflow
Object seems necessary because if you only return a single element. It would only have the type Album and we could not work...
Read more >
Define a Realm Object Model - React Native SDK - MongoDB
Realm guarantees that all objects in a realm conform to the schema for their object type and validates objects whenever they're created, modified,...
Read more >
realm - npm
Start using realm in your project by running `npm i realm`. ... TypeScript icon, indicating that this package has built-in type declarations.
Read more >
How to use the realm.open function in realm - Snyk
Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues...
Read more >
Getting started with Realm for React Native | by mbvissers.eth
Add these lines to your Database.js. We retrieve the books using realm.objects('Book'). This will return a JSON object that we can view. You...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found