Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve type-safety for Grecha tag #82

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

fnky
Copy link

@fnky fnky commented Jan 10, 2022

This PR adds type definitions for the Tag type with interoperability with HTMLElement and types derived from it.

It introduces a IntrinsicElements interface which is a map of element names corresponding with their corresponding HTMLElement subtype. This is used as a way to provide type information inferred from the element name.

It can be further extended with minimum effort;

interface IntrinsicElements {
  // ... more intrinsic elements ...
  form: HTMLFormElement,
}

function form(action: string, url: string) {
  return tag("form").att$("action", action).att$('url', url);
}

Since tag now inters the type from element name ("form"), it returns the correct type Tag<HTMLFormElement> and no longer requires explicit return types or casting.

There is also partial support for augmenting Tag elements with custom methods ending with a dollar-sign ("$"). Although these are not type-safe and has to be managed by the user manually, since there is not an easy way to infer those types.

It does so by utilizing template literals index signature, as introduced in TypeScript 4.4. Therefore this PR also upgrades TypeScript to the latest version (4.5).

@fnky fnky force-pushed the tag-typesafe branch 3 times, most recently from fa03b2e to e7f4e9f Compare January 10, 2022 03:00
@sakgoyal
Copy link

https://github.com/tsoding/emoteJAM/pull/90/files#r1718035530

this is a much better solution. consider doing something like this instead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants