Skip to content

Commit 08c16a2

Browse files
authored
Added back Understanding args section
1 parent b24e5aa commit 08c16a2

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

docs/ember/components.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,35 @@ export default class ArgsDisplay extends Component<ArgsDisplaySignature> {
126126
{{/each}}
127127
</ul>
128128
```
129+
### Understanding `args`
130+
131+
Looking at that example above, Typescript knows what types `this.args` has, but how? In the `constructor` version, we explicitly _named_ the type of the `args` argument. Here, it seems to just work automatically. This works because the type definition for a Glimmer component looks roughly like this:
132+
133+
```typescript
134+
export default class Component {
135+
args: Readonly<Args>;
136+
constructor(owner: unknown, args: Args);
137+
}
138+
```
139+
140+
{% hint style="info" %}
141+
Not sure what’s up with `<Args>` or `<S>` _at all_? We highly recommend the [TypeScript Deep Dive](https://basarat.gitbooks.io/typescript/) book’s [chapter on generics ](https://basarat.gitbooks.io/typescript/docs/types/generics.html) to be quite helpful in understanding this part.
142+
{% endhint %}
143+
144+
The type signature for Component, with `Args extends {} = {}`, means that the component _always_ has a property named `args`
145+
146+
* with the type `Args`
147+
* which can be anything that extends the type `{}` – an object
148+
* and _defaults_ to being just an empty object – `= {}`
149+
150+
This is analogous to the type of `Array` : since you can have an array of `string` , or an array of `number` or an array of `SomeFancyObject` , the type of array is `Array<T>` , where `T` is the type of thing in the array, which TypeScript normally figures out for you automatically at compile time:
151+
152+
```typescript
153+
let a = [1, 2, 3]; // Array<number>
154+
let b = ["hello", "goodbye"]; // Array<string>
155+
```
156+
157+
In the case of the Component, we have the types the way we do so that you can’t accidentally define `args` as a string, or `undefined` , or whatever: it _has_ to be an object. Thus, `Component<Args extends {}>` . But we also want to make it so that you can just write `extends Component` , so that needs to have a default value. Thus, `Component<Args extends {} = {}>`.
129158
130159
## Generic subclasses
131160

0 commit comments

Comments
 (0)