如何根据 Map<K,V>键和值类型进行逻辑?



为了序列化的目的,必须分离不同的Map<K、 V>类型和基于键和值类型的驱动逻辑。如何在Typescript中做到这一点?

例如

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

功能就像

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;
}

typeof(用于基类型(或instanceof(用于类实例(是您要查找的关键字。

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;
}

或者以一种更干净的方式:

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

最新更新