typeof
(used for base types) or instanceof
(used for class instances) are the keywords that would be appropriate in this situation.
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;
}
Alternatively, a cleaner implementation:
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