TypedMap

subclass of Map that checks key/value types.

JSvalueobjectclassexample ⟩ TypedMap

key points:

  • must call superclass constructor super() before using this.

  • use super.method() to call superclass methods in subclass methods.

// superclass
class TypedMap extends Map {
    
    // private properties
    #keyType;
    #valueType;
    
    // ⭐ subclass constructor
    constructor(keyType, valueType, entries) {

        // ⭐ must init new object with `super()` first❗
        super();            // ⭐ superclass constructor

        // ⭐ now `this` is accessable.
        this.#keyType = keyType;
        this.#valueType = valueType;
        
        // type-check/add entries if `entries` provided
        if (entries) {
            // subclass uses its method to help set key/value pairs,
            // make sure all properties are fully intialized before doing this❗
            entries.forEach(([key, value]) => this.set(key, value));
        }
    }

    // ⭐ override superclass method❗
    set(key, value) {
        // type check first, throw error if failed.
        this.#typecheck(key, value);
        // then set [key, value] using superclass method
        super.set(key, value);        // ⭐ superclass method
    }

    // check types
    #typecheck(key, value) {
        
        //  ⭐ destructuring private fields not allowed❓
        // ---------------------------------------------------------
        // const {#keyType: keyType, #valueType: valueType} = this;
        //        ^^^^^^^^ (⛔ SyntaxError: Unexpected identifier)

        const keyType = this.#keyType;
        const valueType = this.#valueType;
        
        if (typeof key !== keyType || typeof value !== valueType) 
            throw new TypeError(`[${key}:${value}] is not of type [${keyType}:${valueType}]`);
    }
}

// export
module.exports = TypedMap;

Last updated