How can I pass an object that can implement an object?

I have the following classes and interfaces:

export interface IBody {
    body : ListBody;
}

export class Element  {
// ...
}

export class Paragraph extends Element implements IBody {
// ...
}

export class Character extends Element {
// ...
}

I have a code where I get an array of objects obtained from an element (more than just a paragraph and a character). In the case of those who implement IBody, I need to take action on the elements in the body.

What is the best way to find out if it implements IBody? Is it "if (element.body! == undefined)"?

And then how do I access it? "var bodyElement = <IBody> element;" gives me an error.

C:/src/jenova/Dev/Merge/AutoTagWeb/client/layout/document/elements/factory.ts(34,27): error TS2012: Cannot convert 'Element' to 'IBody':
    Type 'Element' is missing property 'body' from type 'IBody'.
    Type 'IBody' is missing property 'type' from type 'Element'.

thanks - dave

+4
source share
1 answer

An interface TypeScript , . 7 TypeScript, , .

, "" interface . , , , . :

// // where e has been typed as any, not an Element
var body = <IBody> e; 

, , IBody. , , e Element , , , Element , /, IBody. , - , IBody, .

, Element , IBody, . , . , , any, , , IBody, script.

Element , IBody. any:

function someFeature(e: any) {

} 

, IBody:

function someFeature(e: any) {
     var body :IBody = <IBody> e;    
     // do something
} 

, , prototype . , interface TypeScript , , . , .

:

function someFeature(e: any) {
    var body = <IBody> e;
    if (typeof (body.someFunctionOnBodyInterface) === "undefined") {
        // not safe to use the function
        throw new Error("Yikes!");
    }

    body.someFunctionOnBodyInterface();
}
+16

Source: https://habr.com/ru/post/1537976/


All Articles