vytant / stimulus-decorators

TypeScript decorators for the Stimulus framework
https://npm.im/@vytant/stimulus-decorators
MIT License
12 stars 2 forks source link

Support for optional Targets? #1

Closed hangsu closed 2 years ago

hangsu commented 2 years ago

Thanks for making this! It's been very helpful in our process of adopting Typescript.

Is there any way to declare an optional Target?

this.hasNameTarget isn't declared, and this.nameTarget throws an error if the target doesn't exist. Even if we use a question mark:

@Target nameTarget?: HTMLElement;
vytant commented 2 years ago

Hi @hangsu, glad to hear this library helped you 🥳

As I see Stimulus throws a runtime error if it doesn't find a target you try to access https://github.com/hotwired/stimulus/blob/main/src/core/target_properties.ts#L21

I don't want to modify Stimulus behavior with this library, so in order to solve your problem, I could add an additional @HasTarget decorator which would let you type and access the hasNameTarget property.

The usage of it should look like this:

@Target nameTarget?: HTMLElement;
@HasTarget hasNameTarget!: boolean;

Please let me know if that would be helpful and I'll implement it.

hangsu commented 2 years ago

Thank you for the response!

We're currently using this as a workaround:

readonly hasNameTarget!: boolean;

Which is functionally the same as what you've proposed, so there's probably no need for changes.