惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News and Events Feed by Topic
GbyAI
GbyAI
博客园 - Franky
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
Google DeepMind News
Google DeepMind News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
InfoQ
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
F
Full Disclosure
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
博客园 - 【当耐特】
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Project Zero
Project Zero
量子位
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
美团技术团队
Attack and Defense Labs
Attack and Defense Labs
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
P
Proofpoint News Feed
Schneier on Security
Schneier on Security
Spread Privacy
Spread Privacy
S
SegmentFault 最新的问题
L
LINUX DO - 最新话题
Simon Willison's Weblog
Simon Willison's Weblog
爱范儿
爱范儿
博客园 - 聂微东
A
About on SuperTechFans
PCI Perspectives
PCI Perspectives
D
Docker

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Record Type in TypeScript: A Quick Intro
Dmitri Pavlutin · 2023-04-28 · via Dmitri Pavlutin Blog

The usual way to define a type of an object in TypeScript is using an object type:


interface SalaryInterface {

annual: number

bonus: number

}

const salary: SalaryInterface = { annual: 56000, bonus: 1200 } // OK


or an index signature:


type NumericObject = {

[key: string]: number

}

const salary: NumericObject = { annual: 56000, bonus: 1200 } // OK


These are good ways to define object types.

But Record<K, V>, the third approach, has the benefit of being shorter and more readable. Let's see how to use it in your code.

Table of Contents

  • 1. Record type
  • 2. Record with union key
  • 3. Record benefits
  • 4. Conclusion

1. Record type

Record<K, V> is a generic type that represents an object type which keys are K and values are V.

For example, Record<string, number> is an object type with string keys and number values:


type NumericRecord = Record<string, number>

const salary: NumericRecord = { annual: 56000, bonus: 1200 } // OK


Edit on CodeSandbox

Record<string, number> is permissive regarding the object structure, as long as the keys are strings and values are numbers:


type NumericRecord = Record<string, number>

const salary1: NumericRecord = { annual: 56000 } // OK

const salary2: NumericRecord = { monthly: 8000 } // OK

const salary3: NumericRecord = { } // OK

const salary4: NumericRecord = { foo: 0, bar: 1, baz: -2 } // OK


Edit on CodeSandbox

But Record<string, number> throws a type error if the value of a prop is a string:


type NumericRecord = Record<string, number>

const salary2: NumericRecord = { annual: '56K' } // Type error!


Edit on CodeSandbox

There are 2 simple rules to remember regarding the allowed types of the keys and values. In Record<K, V>:

  • the key type K is restricted to number, string, symbol, including their literals
  • but there is no restriction on the value type V

Let's see some valid record types:


type T1 = Record<string, string> // OK

type T2 = Record<number, number> // OK

type T3 = Record<string, () => void> // OK

type T4 = Record<number | 'key1', boolean> // OK

type T5 = Record<'key1' | 'key2', boolean> // OK

type T6 = Record<string, Record<string, number>> // OK

type T7 = Record<string, { payment: number }> // OK


Edit on CodeSandbox

Types like boolean, object, Function, etc. are not accepted as keys:


type T1 = Record<boolean, number> // Type error!

type T2 = Record<object, number> // Type error!


Edit on CodeSandbox

2. Record with union key

As seen above, Record<string, number> permits any key names in the object. But quite often you need to annotate objects with a fixed set of keys.

The record type accepts a union type as a key, which is useful to fixate the keys.

A union of string literals is a common way to define the key type:


type Keys = 'key1' | 'key2' | 'keyN'


For example, Record<'annual' | 'bonus', number> represents an object which can have only annual and bonus keys:


type Salary = Record<'annual' | 'bonus', number>

const salary1: Salary = { annual: 56000, bonus: 1200 } // OK


Edit on CodeSandbox

Using less than necessary or keys than aren't in the union is prohibited:


type Salary = Record<'annual' | 'bonus', number>

const salary1: Salary = { annual: 56000 } // Type error!

const salary2: Salary = { bonus: 1200 } // Type error!

const salary3: Salary = { } // Type error!

const salary4: Salary = { monthly: 8000 } // Type error!


Edit on CodeSandbox

The record type with union keys is equivalent to the regular object type. The record type has the benefit of not repeating the value type (like the regular object does):


type Salary = Record<'annual' | 'bonus', number>

// is equivalent to

type SalaryObj = {

annual: number

bonus: number

}


3. Record benefits

I prefer record type instead of index signature most of the time. Record syntax is shorter and more readable (altought it's also a matter of taste).

For example, the record parameter is a bit easier to grasp than the index signature parameter:


function logSalary1(salary: Record<string, number>) {

console.log(salary)

}

function logSalary2(salary: { [key: string]: number }) {

console.log(salary)

}


Compared to record type, the index signature doesn't accept literals or a union as key type:


type Salary = {

[key: 'annual' | 'bonus']: number // Type error!

}


Edit on CodeSandbox

4. Conclusion

Record<K, V> is an object type with key type K and value type V.

The key type K can be only number, string, or symbol, including their literals. On the value type V is no restriction.

To limit the keys to a specific set, you can use a union of string literals Record<'key1' | 'key2', V> as the key type.

Check also my post index signatures to learning more about object types.

How often do you use record type?