Typescript Initialisation of List properties
See original GitHub issueGoals
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:
- Created 4 years ago
- Comments:18 (8 by maintainers)
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.
@hadnet Since version 11, it is possible to define models as such:
And then this class can be used when creating and querying data: