Ts中的Record

521 阅读1分钟

今天被问到下面这行代码里的Record是什么,直接蒙了,但是GPT真好用,直接给出了答案。

const [filteredInfo, setFilteredInfo] = useState<Record<string, FilterValue | null>>({});

下面是关于Record的总结。

Record的定义

Record<Keys, Type>

官方定义:Constructs an object type whose property keys are Keys and whose property values are Type. This utility can be used to map the properties of a type to another type.

构建一个对象类型,对象类型的属性key是Keys类型,而数值value是Type类型。可用于将某个类型的属性映射到另一个属性。

type Record<K extends keyof any, T> = { [P in K]: T; };

用法示例

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" },
};

可以将type CatName视为对一个对象属性结构的描述,就是有“miffy”等三个属性。 Record就是将CatName的每个属性都对应到CatInfo类型。

references

www.typescriptlang.org/docs/handbo… juejin.cn/post/711204…