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 Initialisation of List properties

See original GitHub issue

Goals

Say I’ve got a schema like this (in Typescript):

export class Stuff {
	static schema: ObjectSchema = {
		name: 'Stuff',
		primaryKey: 'id',
		properties: {
			id: 'string',
			text: 'string[]',
		},
	};

	id: string;
	text: List<string>;
}

This is a compiler error because id and text aren’t optional and aren’t instantiated in the constructor.

But in this case, what would the constructor actually look like? This is the best I can guess:

constructor() {
	this.id = 'item-1';
	this.text = new List<string>();
}

but

Cannot use 'new' with an expression whose type lacks a call or construct signature.ts(2351)

Expected Results

How do we correctly initialise objects with required lists so the Typescript types match up to the actual object? The goal is to be able to do this:

const stuff = new Stuff();
stuff.text.push('text here');

so if we don’t initialise text with anything then it won’t be there and we’ll be calling push on undefined.

What should the constructor for this model look like?

Actual Results

Can’t figure out how to correctly construct an object with Linking Objects or List property.

Related Stack Overflow

I didn’t ask this question on stack overflow because this question is already there and hasn’t been answered for a month that didn’t get an answer.

Version of Realm and Tooling

  • Realm JS SDK Version: 2.29.1
  • Typescript Version: 3.5.3
  • Node or React Native: Doesn’t matter
  • Client OS & Version: Doesn’t matter
  • Which debugger for React Native: Doesn’t matter

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:18 (8 by maintainers)

github_iconTop GitHub Comments

1reaction
hadnetcommented, Dec 3, 2022

@hadnet Since version 11, it is possible to define models as such:


export class Item extends Realm.Object<Item> {

  _id!: BSON.ObjectId;

  isComplete!: boolean;

  summary!: string;

  owner_id!: string;



  static schema: Realm.ObjectSchema = {

    name: 'Item',

    primaryKey: '_id',

    properties: {

      // This allows us to automatically generate a unique _id for each Item

      _id: {type: 'objectId', default: () => new BSON.ObjectId()},

      // All todo items will default to incomplete

      isComplete: {type: 'bool', default: false},

      summary: 'string',

      owner_id: 'string',

    },

  };

}

And then this class can be used when creating and querying data:


const items = useQuery(Item)

// or

const items = realm.objects(Item)

// or

const items = realm.objectForPrimaryKey(Item, key)



//...

realm.write(() => {

  new Item(realm, { summary: "some test", owner_id: user.id })

})

But this is not the problem, the problem is the Realm.List type. Please, try to reproduce the code I showed you and you’ll see Typescript throwing the error I described. And it doesn’t matter if I use the old syntax or the new babel-plugin syntax, I’m getting the same TS error.

0reactions
takameyercommented, Dec 3, 2022

@hadnet Since version 11, it is possible to define models as such:

export class Item extends Realm.Object<Item> {
  _id!: BSON.ObjectId;
  isComplete!: boolean;
  summary!: string;
  owner_id!: string;

  static schema: Realm.ObjectSchema = {
    name: 'Item',
    primaryKey: '_id',
    properties: {
      // This allows us to automatically generate a unique _id for each Item
      _id: {type: 'objectId', default: () => new BSON.ObjectId()},
      // All todo items will default to incomplete
      isComplete: {type: 'bool', default: false},
      summary: 'string',
      owner_id: 'string',
    },
  };
}

And then this class can be used when creating and querying data:

const items = useQuery(Item)
// or
const items = realm.objects(Item)
// or
const items = realm.objectForPrimaryKey(Item, key)

//...
realm.write(() => {
  new Item(realm, { summary: "some test", owner_id: user.id })
})
Read more comments on GitHub >

github_iconTop Results From Across the Web

TypeScript and field initializers
Working Example. This example shows how to initialize an object using an approximation of a C# field initializer: class ...
Read more >
TypeScript: Documentation - Classes
A field declaration creates a public writeable property on a class: ... Property 'name' has no initializer and is not definitely assigned in...
Read more >
TypeScript - Arrays
An array declaration allocates sequential memory blocks. Arrays are static. This means that an array once initialized cannot be resized. Each memory block ......
Read more >
Object initializer - JavaScript - MDN Web Docs - Mozilla
An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, ...
Read more >
TypeScript Classes
The class in TypeScript is compiled to plain JavaScript function by the ... class calls the super constructor to initialize the parent class...
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