Record<string,any> 在typescript里面?

新手上路,请多包涵

感觉也没有什么限制呀...依然什么东西都能传入。
那这个语法存在的意义是什么,有没有大佬帮忙解惑
image.png

阅读 1.5k
1 个回答

这玩意主要是用来让你声明一个字典对象的啊,因为ts是js的超集,类型注释是为了编译时候发现错误,方便开发者能体验到静态类型的好处。

官网的描述

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.

google的描述:

The Record type in TypeScript is used to create a dictionary of key-value pairs, where the keys and values can have specific types. A Record type is essentially an object type, but it provides a way to specify the types of the keys and values for better type checking and code readability.

案例:

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

// 二
const scoreBoard: Record<"A X" | "A Y" | "A Z" | "B X" | "B Y" | "B Z" | "C X" | "C Y" | "C Z", number> = {
  "A X": 4,
  "A Y": 8,
  "A Z": 3,
  "B X": 1,
  "B Y": 5,
  "B Z": 9,
  "C X": 7,
  "C Y": 2,
  "C Z": 6,
};

// 三
type Quote = {
  quote: string,
  author: string
}

type id = 1 | 2 | 3 | 4 | 5;

type QuotesList = Record<id, Quote>;


const quotes:QuotesList = {
  1: {
    quote: 'There are only two kinds of languages: the ones people complain about and the ones nobody uses.',
    author: 'Bjarne Stroustrup'
  },
  2: {
    quote: 'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.',
    author: 'Martin Fowler'
  },
  3: {
    quote: 'First, solve the problem. Then, write the code.',
    author: 'John Johnson'
    },
  4: {
    quote: 'Java is to JavaScript what car is to Carpet.',
    author: 'Chris Heilmann'
    },
  5: {
    quote: 'Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.',
    author: 'John Woods'
    },  
  // 5: { //will show a syntax error - An object literal cannot have multiple properties with the same name.ts(1117)
  //   quote: 'Truth can only be found in one place: the code.',
  //   author: 'Robert C. Martin'
  // }
  
  // 6: { // error - Object literal may only specify known properties, and '6' does not exist in type 'QuotesList'.ts(2322)
  //   quote: 'SQL, Lisp, and Haskell are the only programming languages that I’ve seen where one spends more time thinking than typing.',
  //   author: 'Philip Greenspun'
  // }
}

其实也并没有什么特别的地方。

你截图的部分,字典对象的key是一个字符串,value是一个any(通用类型)。

logo
Microsoft
子站问答
访问
宣传栏