Trying to understand index signatures in TypeScript

前端 未结 2 1498
刺人心
刺人心 2020-12-19 21:38

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         


        
2条回答
  •  有刺的猬
    2020-12-19 22:10

    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.

提交回复
热议问题