I think I basically got how index signatures work in TypeScript. However, there is one thing I don\'t get. Given the following sample code:
const sales: {[ k
This is just an addition to the accepted answer, because it's totally right
If your aim is to get compile time errors if you don't check if e.g. sales.d
exists/is not undefined
, you could implement your own interface here:
interface SomeDictionary {
{[ key: string ]: T | undefined }
}
const sales: SomeDictionary = {
a: 532,
b: 798,
c: 264
};
// compile time error
const result = sales.a + sales.b;
// working
if(sales.a !== undefined && sales.b !== undefined){
const result = sales.a + sales.b;
}
AFAIK there is no such built-in interface in typescript.
I think index signatures (in your case) make sense if you want to iterate over the keys of an such an object:
const sales: {[ key: string ]: number } = {
a: 532,
b: 798,
c: 264
};
let sum = 0;
for(const key in Object.keys(sales)){
sum = sum + sales[key];
}
I assume there are much more uses cases which are not coming into my mind right now..
To your side question: No, it's not (if you meant Record
from here. Record
does not even compile, because it needs a second type argument. I would say Record
's are not really related to your issue.