Browsed some typescript codes about Tuple, the following code snippet caught my eyes. What does this KeyValuePair look like? How does it achieve the purpose to be a KeyValuePair?
interface KeyValuePair<K, V> extends Array<K | V> {
0: K;
1: V
}
Let us begin with some simple TS objects. What are the shapes of these following TS objects?
let student = {
name: "Joe";
major: "Dirt);
}
study() {
console.log('study ...');
}
getGrade(studentName: string): number {
return 100;
}
myArray: any[] = ['hello', 'Joe', 'Dirt', 'Marketing', 100];
I use simplified notation below.
objectName: (params?) => ...any
The shapes are:
student: { name: string, major: string }
study: () => void
getGrade: (studentName: string) => number
myArray: [0: string, 1: string, 2: string, 3: string, 4: number]
Back to our original question, what is the shape of this code snippet?
interface KeyValuePair<K, V> extends Array<K | V> {
0: K;
1: V
}
The shape is:
KeyValuePair<K,V>: [0: K, 1: V]
Basically, the KeyValuePair extends the Array, and strong type the [0] element to be K, and [1] element to be V, and transform an ordered array into a KeyValuePair or a two-element Tuple.