Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【TypeScript】TypeScript之Record的基本用法 #4

Open
Lydever opened this issue Dec 12, 2021 · 0 comments
Open

【TypeScript】TypeScript之Record的基本用法 #4

Lydever opened this issue Dec 12, 2021 · 0 comments

Comments

@Lydever
Copy link
Owner

Lydever commented Dec 12, 2021

Record<Keys,Type>

构造一个对象类型,其属性key是Keys,属性value是Type。被用于映射一个类型的属性到另一个类型。

简单来说,TypeScript中的Record可以实现定义一个对象的 key 和 value 类型,Record 后面的泛型就是对象键和值的类型。

实例

比如我需要一个cats对象,这个对象里有三个不同的属性,且属性的值必须是数字和字符串
那么可以这样写:

interface CatInfo {
  age: number;
  breed: string;
}
 
type CatName = "mincat" | "licat" | "mordred";
 
const cats: Record<CatName, CatInfo> = {
  mincat: { age: 10, breed: "小猫er" },
  licat: { age: 5, breed: "李猫er" },
  mordred: { age: 16, breed: "无名猫er" },
};
 
cats.licat;
 
const cats: Record<CatName, CatInfo>

学习文档:https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeystype

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant