-
Notifications
You must be signed in to change notification settings - Fork 424
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add some documentation for using stimulus with typescript (#540)
- Loading branch information
1 parent
ffb8d25
commit 30933d6
Showing
1 changed file
with
75 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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). |