Skip to content

Commit

Permalink
Add some documentation for using stimulus with typescript (#540)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-schranz authored May 1, 2022
1 parent ffb8d25 commit 30933d6
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions docs/reference/using_typescript.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Using Typescript

Stimulus itself is written [TypeScript](https://www.typescriptlang.org/)
and provides types directly over its package.
The following documentation should make it clear how to define types for
stimulus properties.

## Define Controller Element Type

By default, the `element` of the controller is from type `Element`.
If the element expected type is as example `HTMLFormElement` it can
be defined this way:

```ts
import { Controller } from '@hotwired/stimulus';

export default class MyController extends Controller<HTMLFormElement> {
submit() {
new FormData(this.element)
}
}
```

## Define Controller Value Type

To define the type of configured values is possible
over the declare feature of TypeScript:

```ts
import { Controller } from '@hotwired/stimulus';

export default class MyController extends Controller {
static values = {
code: String,
};

declare readonly codeValue: string;
}
```

> The `declare` avoids override of the exist stimulus property and just define the type for TypeScript.
## Define Controller Target Type

To define the type of configured targets is possible
over the declare feature of TypeScript:

```ts
import { Controller } from '@hotwired/stimulus';

export default class MyController extends Controller {
static targets = [
'input'
];

declare readonly inputTarget: HTMLInputElement;
}
```

> The `declare` avoids override of the exist stimulus property and just define the type for TypeScript.
## Custom properties amd methods

Other custom properties is possible to define the TypeScript way
on the controller class:

```ts
import { Controller } from '@hotwired/stimulus';

export default class MyController extends Controller {
container: HTMLElement;
}
```

Read more about it in the [TypeScript Documentation](https://www.typescriptlang.org/docs/handbook/intro.html).

0 comments on commit 30933d6

Please sign in to comment.