Skip to content

Commit b24e5aa

Browse files
authored
Reflect the introduction of Component Signatures
This PR follows [feedback](https://discuss.emberjs.com/t/component-arguments-and-typescript-whats-the-right-approach/19761) from @chriskrycho on Ember Discuss, and aims to reflect the introduction of Component Signatures. Hopefully this isn't too heavy handed but it seemed to me that previous sections belonged to a time when `args` could be empty object. As defining a Signature is a prerequisite for calling `this.args` it felt right to remove them?
1 parent 7ca7c5d commit b24e5aa

File tree

1 file changed

+41
-85
lines changed

1 file changed

+41
-85
lines changed

docs/ember/components.md

Lines changed: 41 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -36,19 +36,46 @@ export default class Counter extends Component {
3636

3737
Notice that there are no type declarations here – but this _is_ actually a well-typed component. The type of `count` is `number`, and if we accidentally wrote something like `this.count = "hello"` the compiler would give us an error.
3838

39-
## Adding arguments
39+
## Adding arguments and giving them a type
4040

4141
So far so good, but of course most components aren’t quite this simple! Instead, they’re invoked by other templates and they can invoke other components themselves in their own templates.
4242

43-
Glimmer components can receive both _arguments_ and _attributes_ when they are invoked. When you are working with a component’s backing class, you have access to the arguments but _not_ to the attributes. The arguments are passed to the constructor, and then available as `this.args` on the component instance afterward. Let’s imagine a component which just logs the names of its arguments when it is first constructed:
43+
Glimmer components can receive both _arguments_ and _attributes_ when they are invoked. When you are working with a component’s backing class, you have access to the arguments but _not_ to the attributes. The arguments are passed to the constructor, and then available as `this.args` on the component instance afterward.
44+
45+
Since the implementation of [RFC 748], Glimmer and Ember components accept a `Signature` type parameter as part of their definition. This parameter is expected to be an object type with (up to) three members: `Args`, `Element` and `Blocks`.
46+
47+
[rfc 748]: https://github.com/emberjs/rfcs/pull/748
48+
49+
`Args` represents the arguments your component accepts. Typically this will be an object type mapping the names of your args to their expected type. For example:
50+
51+
```
52+
export interface MySignature {
53+
Args: {
54+
arg1: string;
55+
arg2: number;
56+
arg3: boolean;
57+
}
58+
}
59+
```
60+
If no `Args` key is specified, it will be a type error to pass any arguments to your component. You can read more about `Element` and `Block` in the Glint [Component Signatures documentation](https://typed-ember.gitbook.io/glint/using-glint/ember/component-signatures).
61+
62+
Let’s imagine a component which just logs the names of its arguments when it is first constructed. First, we must define the Signature and pass it into our component, then we can use the `Args` member in our Signature to set the type of `args` in the constructor:
4463

4564
```typescript
4665
import Component from '@glimmer/component';
4766

4867
const log = console.log.bind(console);
4968

50-
export default class ArgsDisplay extends Component {
51-
constructor(owner: unknown, args: {}) {
69+
export interface ArgsDisplaySignature {
70+
Args: {
71+
arg1: string;
72+
arg2: number;
73+
arg3: boolean;
74+
}
75+
}
76+
77+
export default class ArgsDisplay extends Component<ArgsDisplaySignature> {
78+
constructor(owner: unknown, args: ArgsDisplaySignature['Args]) {
5279
super(owner, args);
5380

5481
Object.keys(args).forEach(log);
@@ -69,24 +96,22 @@ Notice that we have to start by calling `super` with `owner` and `args`. This ma
6996
This might change in the future! If TypeScript eventually adds [support for “variadic kinds”](https://github.com/Microsoft/TypeScript/issues/5453), using `...arguments` could become safe.
7097
{% endhint %}
7198
72-
The types for `owner` here and `args` line up with what the `constructor` for Glimmer components expect. The `owner` is specified as `unknown` because this is a detail we explicitly _don’t_ need to know about. The `args` are `{}` because a Glimmer component _always_ receives an object containing its arguments, even if the caller didn’t pass anything: then it would just be an empty object.
73-
74-
`{}` is an empty object type – all objects extend from it, but there will be no properties on it. This is distinct from the `object` type, which the TypeScript docs describe as:
75-
76-
> any thing that is not `number`, `string`, `boolean`, `symbol`, `null`, or `undefined`.
77-
78-
If we used `object`, we could end up with TypeScript thinking `args` were an array, or a `Set`, or anything else that isn’t a primitive. Since we have `{}`, we _know_ that it's an object.
79-
80-
{% hint style="info" %}
81-
For some further details, check out [this blog post](https://mariusschulz.com/blog/the-object-type-in-typescript).
82-
{% endhint %}
99+
The types for `owner` here and `args` line up with what the `constructor` for Glimmer components expect. The `owner` is specified as `unknown` because this is a detail we explicitly _don’t_ need to know about. The `args` are the `Args` from the Signature we defined.
83100
84101
The `args` passed to a Glimmer Component [are available on `this`](https://github.com/glimmerjs/glimmer.js/blob/2f840309f013898289af605abffe7aee7acc6ed5/packages/%40glimmer/component/src/component.ts#L12), so we could change our definition to return the names of the arguments from a getter:
85102
86103
```typescript
87104
import Component from '@glimmer/component';
88105

89-
export default class ArgsDisplay extends Component {
106+
export interface ArgsDisplaySignature {
107+
Args: {
108+
arg1: string;
109+
arg2: number;
110+
arg3: boolean;
111+
}
112+
}
113+
114+
export default class ArgsDisplay extends Component<ArgsDisplaySignature> {
90115
get argNames(): string[] {
91116
return Object.keys(this.args);
92117
}
@@ -102,75 +127,6 @@ export default class ArgsDisplay extends Component {
102127
</ul>
103128
```
104129
105-
### Understanding `args`
106-
107-
Now, looking at that bit of code, you might be wondering how it knows what the type of `this.args` is. 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:
108-
109-
```typescript
110-
export default class Component<Args extends {} = {}> {
111-
readonly args: Args;
112-
113-
constructor(owner: unknown, args: Args);
114-
}
115-
```
116-
117-
{% hint style="info" %}
118-
Not sure what’s up with `<Args>` _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.
119-
{% endhint %}
120-
121-
The type signature for Component, with `Args extends {} = {}`, means that the component _always_ has a property named `args`
122-
123-
* with the type `Args`
124-
* which can be anything that extends the type `{}` – an object
125-
* and _defaults_ to being just an empty object – `= {}`
126-
127-
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:
128-
129-
```typescript
130-
let a = [1, 2, 3]; // Array<number>
131-
let b = ["hello", "goodbye"]; // Array<string>
132-
```
133-
134-
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 {} = {}>`.
135-
136-
### Giving `args` a type
137-
138-
Now let’s put this to use. Imagine we’re constructing a user profile component which displays the user’s name and optionally an avatar and bio. The template might look something like this:
139-
140-
```text
141-
<div class='user-profile' ...attributes>
142-
{{#if this.avatar}}
143-
<img src={{this.avatar}} class='user-profile__avatar'>
144-
{{/if}}
145-
<p class='user-profile__bio'>{{this.userInfo}}</p>
146-
</div>
147-
```
148-
149-
Then we could capture the types for the profile with an interface representing the _arguments_:
150-
151-
```typescript
152-
import Component from '@glimmer/component';
153-
import { generateUrl } from '../lib/generate-avatar';
154-
155-
interface User {
156-
name: string;
157-
avatar?: string;
158-
bio?: string;
159-
}
160-
161-
export default class UserProfile extends Component<User> {
162-
get userInfo(): string {
163-
return this.args.bio ? `${this.args.name} ${this.args.bio}` : this.args.name;
164-
}
165-
166-
get avatar(): string {
167-
return this.args.avatar ?? generateUrl();
168-
}
169-
}
170-
```
171-
172-
Assuming the default `tsconfig.json` settings \(with `strictNullChecks: true`\), this wouldn't type-check if we didn't _check_ whether the `bio` argument were set.
173-
174130
## Generic subclasses
175131
176132
If you'd like to make your _own_ component subclass-able, you need to make it generic as well.

0 commit comments

Comments
 (0)