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 TypeScript support for element creation in Cash-dom #435

Open
amirfarzamnia opened this issue Jan 4, 2025 · 1 comment
Open

Comments

@amirfarzamnia
Copy link

Feature description

When working with Vanilla.js, TypeScript, and Webpack, I encountered an issue with creating elements in Cash-dom. In my previous setup, using plain document.createElement('img'), TypeScript was able to infer the correct type (HTMLImageElement). However, when using Cash-dom, I ran into a type error when trying to create elements like images.

Example:

Object.assign(document.createElement('img'), {
  src: 'https://example.com/example.png'
} satisfies Partial<HTMLImageElement>);

This works fine in Vanilla.js with TypeScript, but with Cash-dom, I receive the following error:

Object literal may only specify known properties, and 'src' does not exist in type 'Document | HTMLElement | Element | Cash'.ts(2353)

The issue arises because Cash-dom doesn't automatically recognize the context as an HTMLImageElement, unlike document.createElement('img'), which TypeScript correctly infers.

Proposed solution

It would be beneficial to improve TypeScript support in Cash-dom to allow automatic recognition of specific element types (like HTMLImageElement) when creating elements.

An ideal solution would be something like this:

declare const cash: {
  (selector: '<img>', context?: HTMLImageElement): Cash;
  (selector?: Selector, context?: Context | Cash): Cash;
} & CashStatic;

This would ensure that Cash-dom correctly infers the type for elements like HTMLImageElement when using methods like createElement.

Feature motivation

This enhancement would provide better TypeScript type inference and make it easier to work with Cash-dom in a TypeScript project, improving developer experience and reducing type-related errors.

Is this feature present in jQuery? No

@amirfarzamnia
Copy link
Author

This is the code I'm using in Cash-dom:

$('<img>', {
src: 'https://example.com/example.png'
})

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

No branches or pull requests

1 participant