Skip to content

Commit faf5b3d

Browse files
authored
Merge pull request #1485 from muziejus/import-types-of-models
Encourage the use of type-only imports
2 parents 952ec83 + 1f7514f commit faf5b3d

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

docs/ember-data/models.md

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,17 @@ export default class User extends Model {
5858
}
5959
```
6060

61-
## `@belongsTo`
61+
## Relationships
62+
63+
Relationships between models in Ember Data rely on importing the related models, like `import User from './user';`. This, naturally, can cause a recursive loop, as `/app/models/post.ts` imports `User` from `/app/models/user.ts`, and `/app/models/user.ts` imports `Post` from `/app/models/post.ts`. Recursive importing triggers an [`import/no-cycle`](https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-cycle.md) error from eslint.
64+
65+
To avoid these errors, use of [type-only imports](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html), available since TypeScript 3.8:
66+
67+
```ts
68+
import type User from './user';
69+
```
70+
71+
### `@belongsTo`
6272

6373
The type returned by the `@hasMany` decorator depends on whether the relationship is `{ async: true }` \(which it is by default\).
6474

@@ -70,8 +80,8 @@ So, for example, you might define a class like this:
7080
```typescript
7181
import Model, { belongsTo } from '@ember-data/model';
7282
import DS from 'ember-data'; // NOTE: this is a workaround, see discussion below!
73-
import User from './user';
74-
import Site from './site';
83+
import type User from './user';
84+
import type Site from './site';
7585

7686
export default class Post extends Model {
7787
@belongsTo('user')
@@ -89,7 +99,7 @@ These are _type_-safe to define as always present, that is to leave off the `?`
8999

90100
Note, however, that this type-safety is not a guarantee of there being no runtime error: you still need to uphold the contract for non-async relationships \(that is: loading the data first, or side-loading it with the request\) to avoid throwing an error!
91101

92-
## `@hasMany`
102+
### `@hasMany`
93103

94104
The type returned by the `@hasMany` decorator depends on whether the relationship is `{ async: true }` \(which it is by default\).
95105

@@ -102,8 +112,8 @@ So, for example, you might define a class like this:
102112
import Model, { hasMany } from '@ember-data/model';
103113
import EmberArray from '@ember/array';
104114
import DS from 'ember-data'; // NOTE: this is a workaround, see discussion below!
105-
import Comment from './comment';
106-
import User from './user';
115+
import type Comment from './comment';
116+
import type User from './user';
107117

108118
export default class Thread extends Model {
109119
@hasMany('comment')

0 commit comments

Comments
 (0)