Home > Software engineering >  typescript object dynamic key type
typescript object dynamic key type

Time:09-20

I have some coding style about Typescript object types, following is a sample:

interface Stats {
  total: number;
  count: number;
  average: number;
}

interface Groups {
  [name: string]: Stats;
}

const groups: Groups = {
  someGroupName: {
    total: 30,
    count: 3,
    average: 10,
  },
  someOtherGroupName: {
    total: 60,
    count: 3,
    average: 20,
  },
};

const { someGroupName } = groups; // someGroup is Stats, that's good.

const someVariable = 'noExistKey'; 
const foundStat = groups[someVariable]; // undeinfed
It's not good and no matter what I type, foundStat will return Stats type.

enter image description here

Is that possible to check the correct type for this coding type obj[variable] ?

CodePudding user response:

Yes, you are looking for noUncheckedIndexedAccess. It's a compiler option that makes X[K] return T | undefined instead of T.

const foundStat = groups[someVariable];
//    ^? Stat | undefined

foundStat.average // error because it could be undefined

Playground

Note that even when you provide the correct key i.e. groups["someGroupName"] it will still produce Stat | undefined.

  • Related