tmokmss
tmokmss

Reputation: 538

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

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?

Upvotes: 29

Views: 9656

Answers (2)

Hao-Jung Hsieh
Hao-Jung Hsieh

Reputation: 843

There are different, It just the same result on your code the Record is actually the same to the fellowing.

/**
 * Construct a type with a set of properties K of type T
 */
type Record<K extends keyof any, T> = {
    [P in K]: T;
};

It may work different when using with generic.

Upvotes: -1

Ricky Mo
Ricky Mo

Reputation: 7698

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)

Upvotes: 26

Related Questions