typescript

Extending a TypeScript type by adding new element in the array of a field


I want to tell TS that the type is as it expects with only a slight alteration of adding a field. The trick is that I don't need to add the field to the type itself but to the set of available elements in the collection of one of its fields.

This works but is verbose and clunky.

const explicit = this.element.nativeElement.attributes.banana;

I could improve readability.

const pre = this.element.nativeElement;
const implicit = pre.attributes.banana;

In fact, I already have such field. However, due to other considerations, it's typed as follows, making it bark at me due to incorrect typing.

const typed = this.element.nativeElement as HTMLElement;
const boohoo = typed.attributes.banana;

Naturally, I could cheat. But writing TS and using any is like getting a flashlight and making it driven by solar energy.

const typed = this.element.nativeElement as HTMLElement;
const weehee = (typed.attributes as any).banana;

That's why I want to say, hey TS, lets add a new field like as HTMLElement & { banana: string } but in such a way that the banana becomes a part of the attributes and not the element itself.

const retyped = this.element.nativeElement as HTMLElement & { ??? };

I can't figure out how and I've tried going through all the examples I could find. I know it's possible, because it's weirdly coherent. I can't see how, other than declaring a new type explicitly. And without cheating.


Solution

  • You could extend your cast type like that:

    HTMLElement & { attributes: { banana : string } }