Home > other >  What is the difference between Record<K, T> and { [key: K]: T } in TypeScript?
What is the difference between Record<K, T> and { [key: K]: T } in TypeScript?

Time:05-31

Hi what's the difference between Record<K, T> and { [key: K]: T } in TypeScript? For example they seem to work the same in the below code.

const obj1: Record<string, number> = {a: 1, b: 2};
const obj2: { [key: string]: number } = {a: 1, b: 2};

Is there any difference between them?

CodePudding user response:

No difference in your case, but it is possible to do more with Record. Consider the official example

interface CatInfo {
  age: number;
  breed: string;
}
 
type CatName = "miffy" | "boris" | "mordred";
 
const cats: Record<CatName, CatInfo> = {
  miffy: { age: 10, breed: "Persian" },
  boris: { age: 5, breed: "Maine Coon" },
  mordred: { age: 16, breed: "British Shorthair" },
};

You cannot replace it with

const cats2: {[key:CatName]: CatInfo} = {
    miffy: { age: 10, breed: "Persian" },
    boris: { age: 5, breed: "Maine Coon" },
    mordred: { age: 16, breed: "British Shorthair" },
};

because this gives you error An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.(1337)

  • Related