Jeff Jeff - 2 months ago 14
TypeScript Question

TypeScript Class Being Used In Cast Not Loading

I've created a model in TypeScript that I'm using in a cast. When running the application, the model is not loaded and I'm unable to use any functions on that model.

Model

export class DataIDElement extends HTMLElement {
get dataID(): number {
var attributes: NamedNodeMap = this.attributes;
var dataIDAttribute: Attr = attributes.getNamedItem("data-id");

if (!dataIDAttribute) {
//throw error
}

var value: number = Number(dataIDAttribute.value);
return value;
}
}


Angular Component (Where model is being imported)

import { DataIDElement } from '../../models/dataIdElement';

export class PersonComponent
{
personClicked(event: KeyboardEvent): void {
var element: DataIDElement = <DataIDElement>event.target;

// This code always returns undefined (model isn't loaded)
var personID: number = element.dataID;
}
}

Answer

What you are doing there is a type assertion. That only overwrites the type inference of the compiler to make it believe that event.target is of the type DataIDElement. It doesn't create a new instance of DataIDElement.

If you want to create an instance of DataIDElement you need to create it using new.

DataIDElement would look something like this:

export class DataIDElement extends HTMLElement {
    constructor(private target: HTMLElement) {}
    get dataID(): number {
        var attributes: NamedNodeMap = this.target.attributes;
        var dataIDAttribute: Attr = attributes.getNamedItem("data-id");

        if (!dataIDAttribute) { 
            //throw error
        }

        var value: number = Number(dataIDAttribute.value);
        return value;
    }
}

And would be used like this:

import { DataIDElement } from '../../models/dataIdElement';

export class PersonComponent
{
    personClicked(event: KeyboardEvent): void {
        var element: DataIDElement = new DataIDElement(event.target);

        // This code always returns undefined (model isn't loaded)
        var personID: number = element.dataID;
    }
}