Computed Properties
There are two variants of Ember’s computed properties you may encounter:
  • the decorator form used with native (ES6) classes
  • the callback form used with classic classes (based on EmberObject)

Decorator form

1
import Component from '@ember/component';
2
import { computed } from '@ember/object/computed';
3
4
export default class UserProfile extends Compoennt {
5
name = 'Chris';
6
age = 33;
7
8
@computed('name', 'age')
9
get bio() {
10
return `${this.name} is `${this.age}` years old!`;
11
}
12
}
Copied!
Note that it is impossible for @computed to know whether the keys you pass to it are allowed or not. Migrating to Octane eliminates this issue, since you mark reactive root state with @tracked and leave getters undecorated, rather than vice versa.

Callback form

Computed properties in the classic object model take a callback instead:
1
import Component from '@ember/component';
2
import { computed } from '@ember/object/computed';
3
4
const UserProfile = Component.extend({
5
name: 'Chris',
6
age: 32,
7
8
bio: computed('name', 'age', function() {
9
return `${this.get('name')} is `${this.get('age')}` years old!`;
10
}),
11
})
12
13
export default UserProfile;
Copied!
This definition will not type-check, however. You will need to explicitly write out a this type for computed property callbacks for get and set to type-check correctly:
1
import Component from '@ember/component';
2
import { computed } from '@ember/object/computed';
3
4
const UserProfile = Component.extend({
5
name: 'Chris',
6
age: 32,
7
8
bio: computed('name', 'age', function(this: UserProfile) {
9
// ^---------------^
10
// `this` tells TS to use `UserProfile` for `get` and `set` lookups;
11
// otherwise `this.get` below would not know the types of `'name'` or
12
// `'age'` or even be able to suggest them for autocompletion.
13
return `${this.get('name')} is `${this.get('age')}` years old!`;
14
}),
15
})
16
17
export default UserProfile;
Copied!
Note that this does not always work: you may get warnings from TypeScript about the item being defined in terms of itself.
Accordingly, we strongly recommend migrating classic classes to ES native classes before adding TypeScript!
Last modified 1yr ago
Export as PDF
Copy link
Edit on GitHub