简体   繁体   中英

Typescript: Compare if the object that is the type of an Interface is equal to another object has the same Interface type

I have the following interface:

export interface IDateRangeOperation {
    getDateRange(): DateRange;
}

And have the following class:

export class DefaultRangeItem {
    name: String;
    operation: IDateRangeOperation;
    constructor(name: String, operation: IDateRangeOperation){
        this.name = name;
        this.operation = operation;

    }
    isEqual(defaultRangeItem: DefaultRangeItem): Boolean {
        return this.name === defaultRangeItem.name;
    }
    getDateRange(): DateRange {
        return this.operation.getDateRange();
    }
}

I have several classes that Implements the IDateRangeOperation

What I want is a way to compare, in the isEqual function , the operation object of the two DefaultRangesItems (on that receives on the isEqual function with the present on the current DefaultRangeItem )

As the @jcalz said in the comments, this is a duplicated question, but I will answer it by pointing what I change to make it work, based on the information given on this post . Remember:

Typescript is a typed superset of Javascript that compiles to plain Javascript.

So, if works in javascript, works in typescript.

Back to my case, I change this:

isEqual(defaultRangeItem: DefaultRangeItem): Boolean {
    return this.name === defaultRangeItem.name;
}

To this:

isEqual(defaultRangeItem: DefaultRangeItem): Boolean {
        return this.key === defaultRangeItem.key && this.name === defaultRangeItem.name &&
                this.operation.constructor === defaultRangeItem.operation.constructor;
    }

And know the isEqual function also validate the type of the object that the operation: IDateRangeOperation; is holding.

Important note: This only verifies if the objects operation are instance of the same class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM