so I have a function which will take string of upperCase letters and each individual letter has value as stated in alphabet object. Yet I have troubles writing it in typescript. Here is code which is working in javascript:
export const alphabet = {
A: 1,
B: 2,
C: 3,
D: 4,
E: 5,
F: 6,
G: 7,
H: 8,
I: 9,
J: 10,
K: 11,
L: 12,
M: 13,
N: 14,
O: 15,
P: 16,
Q: 17,
R: 18,
S: 19,
T: 20,
U: 21,
V: 22,
W: 23,
X: 24,
Y: 25,
Z: 26,
};
const adressDecoder = () => {
let startColumnString = ["A", "A"]
let startColumn = startColumnString.reduce((prev, curr) => {
if (prev === 0) return alphabet[curr];
return prev * 26 alphabet[curr];
}, 0);
console.log(startColumn);
};
adressDecoder()
So I tried to cast type to alphabet object, but I did it incorrect, and now console.log() returns undefined
interface Alphabet {
[key: string]: number;
}
export const alphabet: Alphabet = {
A: 1,
B: 2,
C: 3,
D: 4,
E: 5,
F: 6,
G: 7,
H: 8,
I: 9,
J: 10,
K: 11,
L: 12,
M: 13,
N: 14,
O: 15,
P: 16,
Q: 17,
R: 18,
S: 19,
T: 20,
U: 21,
V: 22,
W: 23,
X: 24,
Y: 25,
Z: 26,
};
const adressDecoder = () => {
let startColumnString = ["A", "A"]
let startColumn = startColumnString.reduce((prev: number, curr: string) => {
if (prev === 0) {
let result: number = alphabet[curr];
return result;
}
let result: number = prev * 26 alphabet[curr];
return result;
}, 0);
console.log(startColumn);// should be 27
};
adressDecoder()
How to properly define interface/type of alpabet object?
CodePudding user response:
To define properly type of alpabet object use type AlphabetType = keyof typeof alphabet;
like so
export const alphabet = {
A: 1,
B: 2,
C: 3,
D: 4,
E: 5,
F: 6,
G: 7,
H: 8,
I: 9,
J: 10,
K: 11,
L: 12,
M: 13,
N: 14,
O: 15,
P: 16,
Q: 17,
R: 18,
S: 19,
T: 20,
U: 21,
V: 22,
W: 23,
X: 24,
Y: 25,
Z: 26
} as const;
type AlphabetType = keyof typeof alphabet;
CodePudding user response:
It will return undefined
because the first reduce
iteration, the prev
variable will be equal to zero, and with if
condition
if (prev === 0) return alphabet[curr];
There is no key in the alphabet
object equal to AA