Soy nuevo en TypeScript y estoy tratando de convertir mi propia forma de vincular componentes JS (vainilla) a elementos DOM en TypeScript, pero estoy luchando mucho. Esto es lo que tengo hasta ahora. Si bien entiendo por qué el compilador se queja, no sé cómo resolverlo.
index.ts (punto de entrada)
import App from './App' import bindings from './bindings' const app = new App(); app.bind(bindings);fijaciones.ts
import Foo from './components/Foo'; type Binding = { component: Function; name: string; options?: object; } export default [ { component: Foo, name: 'foo' }, // Would get bound to .js-foo elements ] as Binding[];App.ts (truncado por brevedad)
export default class App { bind(bindings: Binding[] = []) { for (const binding of bindings) { document.body.querySelectorAll(`.js-${binding.name}`).forEach($el => { // Initialize a custom object on the DOM element to store component instance const app: { [key: string]: object } = {}; $el.app = $el.app ?? app // What I'm trying to accomplish in non type checking code: $el.app[binding.name] = new binding.component(binding.options ?? {}); // Left-hand error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. // No index signature with a parameter of type 'string' was found on type '{}'.ts(7053) // Right-hand error: This expression is not constructable. // Type 'Function' has no construct signatures.ts(2351) }); } } }¡Cualquier ayuda es muy apreciada!
TS se queja porque $el.app no necesariamente tiene una clave con el nombre arbitrario de binding.name . Está configurando un tipo válido para este caso de uso al definir const app , pero no hay garantía de que $el.app tome ese valor, debido al operador nulo.
La solución de fuerza bruta es simplemente lanzar $el.app :
$el.app = ($el.app ?? {}) as { [key: string]: object }; Function y las clases se manejan de manera diferente en mecanografiado. Si desea una clase genérica, puede usar este tipo:
type ClassConstructor = new (...args: any[]) => unknown;O mejor aún, cree una clase base y utilícela como tipo:
class BaseBindingComponent {} . . . class Foo extends BaseBindingComponent {} . . . type Binding = { component: BaseBindingComponent; name: string; options?: object; }