Home > Back-end >  How to do logic based on Map<K,V> key and value types?
How to do logic based on Map<K,V> key and value types?

Time:02-03

For serialization purposes one has to separate different Map<K,V> types and drive logic based on the key and the value types. How can that be done in Typescript?

e.g.

const stringAndNumberPairs: Map<string, number> = new Map<string, number>([['text', 1]]);
const stringAndStringPairs: Map<string, string> = new Map<string, string>([['text', 'more text']]);

and function would be something like

function serialize(input: any): string {
  let output: string = "";
  if (type of K is number) {
    output  = "Key is number"; 
  }

  if (type of V is string) {
    output  = "Value is string";
  }
  else if (type of V is number) {
    output  = "Value is number";
  }

  return output;
}

CodePudding user response:

typeof (for base types) or instanceof (for class instances) are the keywords you are looking for.

class Foo { }


function serialize<K, V extends any>(map: Map<K, V>): string {
    let output: string = "";

    Array.from(map.entries()).forEach(([k, v]) => {
        if (typeof k === 'number') {
            output  = "Key is number";
        }

        if (typeof v === 'string') {
            output  = "value if string"
        }

        if (v instanceof Foo) {
            output  = "value if string"
        }
    });
    return output;
}

or in a much cleaner way :

function serialize<K, V extends any>(map: Map<K, V>): string[][] {

  const output = Array.from(map.entries()).map(([k, v]) => {
    return [
      { condition: typeof k === 'number', label: 'Key is number' },
      { condition: typeof v === 'string', label: "value is string" },
      { condition: v instanceof Foo, label: 'value is class Foo' }

    ].filter((c) => c.condition).map((c) => c.label)  // you could join() here

  });
  return output  // also join() here
}

https://www.typescriptlang.org/play?ssl=16&ssc=2&pln=1&pc=1#code/MYGwhgzhAEBiD29oG9oF8CwAob2BmArgHbAAuAlvEdBAKYBO5YI5AXrQDwDSANNAGrRaAD1K0iAExhgiATwB8ACgC2YAA4AuaAFl13Pv3kBKLRFKMiAcwDaAXTspcWaNGBUz0eAVJrv0ALzQAIL09GCyAHR49PDKKuoR4ubktBCKRkYRqmqKitYA1nwAbrZGAfKOzi7Q9LSkBPTU1tjV1ahukuQUVFqksmq08HjQ QH gQDkRATKAEYME3zg8yBaE1y0stDkMNNzC g8La0orlQSXZREvf2Dw0Vjk2YWlovQy7Sr0ABERcwEtG2MGe5Cs30Ox1a7XOlx60AeoLMMmAdzgiCWYBWaz IABQNc4CgaPgE3QTlatii5BAYnouWAZX8FWAEQ6F26REy2XpjOZEQ IDK0AA9MLoLIvK4ZNAAFbwUHpaAACwYtHJ6CMAG5jrV6o1PN5fKQXKLoMwIEg5Qqyiratg0EA
  •  Tags:  
  • Related