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

推荐订阅源

Recent Commits to openclaw:main
Recent Commits to openclaw:main
L
LangChain Blog
月光博客
月光博客
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 【当耐特】
宝玉的分享
宝玉的分享
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
博客园_首页
T
Tailwind CSS Blog
P
Proofpoint News Feed
雷峰网
雷峰网
D
Darknet – Hacking Tools, Hacker News & Cyber Security
IT之家
IT之家
V
Vulnerabilities – Threatpost
阮一峰的网络日志
阮一峰的网络日志
C
CERT Recently Published Vulnerability Notes
Attack and Defense Labs
Attack and Defense Labs
S
Schneier on Security
Security Archives - TechRepublic
Security Archives - TechRepublic
L
Lohrmann on Cybersecurity
V
Visual Studio Blog
云风的 BLOG
云风的 BLOG
WordPress大学
WordPress大学
The Register - Security
The Register - Security
N
Netflix TechBlog - Medium
Hugging Face - Blog
Hugging Face - Blog
Project Zero
Project Zero
博客园 - 叶小钗
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
Latest news
Latest news
S
SegmentFault 最新的问题
C
Cyber Attacks, Cyber Crime and Cyber Security
Google Online Security Blog
Google Online Security Blog
Recorded Future
Recorded Future
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Hacker News - Newest:
Hacker News - Newest: "LLM"
腾讯CDC
L
LINUX DO - 最新话题
Google DeepMind News
Google DeepMind News
P
Privacy International News Feed
I
InfoQ
F
Fortinet All Blogs
Vercel News
Vercel News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
T
Tenable Blog
B
Blog RSS Feed

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro 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 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
Index Signatures in TypeScript
Dmitri Pavlutin · 2021-09-23 · via Dmitri Pavlutin Blog

You have 2 objects that describe the salary of 2 software developers:


const salary1 = {

baseSalary: 100_000,

yearlyBonus: 20_000

};

const salary2 = {

contractSalary: 110_000

};


You want to implement a function that returns the total remuneration based on the salary object:


function totalSalary(salaryObject: ???) {

let total = 0;

for (const name in salaryObject) {

total += salaryObject[name];

}

return total;

}

console.log(totalSalary(salary1)); // => 120_000

console.log(totalSalary(salary2)); // => 110_000


How would you annotate salaryObject parameter of totalSalary() function to accept objects with key as string and value as number?

The answer is to use an index signature!

Let's find what are TypeScript index signatures and when they're needed.

Table of Contents

  • 1. Why index signature
  • 2. Index signature syntax
  • 3. Index signature caveats
    • 3.1 Non-existing properties
    • 3.2 String and number key
  • 4. Index signature vs Record
  • 5. Conclusion

1. Why index signature

The idea of the index signatures is to type objects of unknown structure when you only know the key and value types.

An index signature fits the case of the salary parameter: the function should accept salary objects of different structures — just make sure that object values are numbers.

Let's annotate the salaryObject parameter with an index signature:


function totalSalary(salaryObject: { [key: string]: number }) {

let total = 0;

for (const name in salaryObject) {

total += salaryObject[name];

}

return total;

}

console.log(totalSalary(salary1)); // => 120_000

console.log(totalSalary(salary2)); // => 110_000


{ [key: string]: number } is the index signature, which tells TypeScript that salaryObject has to be an object with string type as key and number type as value.

Now the totalSalary() accepts as arguments both salary1 and salary2 objects, since they are objects with number values.

However, the function would not accept an object that has, for example, strings as values:


const salary3 = {

baseSalary: '100 thousands'

};

// Type error:

// Argument of type '{ baseSalary: string; }' is not assignable to parameter of type '{ [key: string]: number; }'.

// Property 'baseSalary' is incompatible with index signature.

// Type 'string' is not assignable to type 'number'.

totalSalary(salary3);


2. Index signature syntax

The syntax of an index signature is simple and looks similar to the syntax of a property. But with one difference: write the type of the key inside the square brackets: { [key: KeyType]: ValueType }.

Here are a few examples of index signatures.

string type is the key and value:


interface StringByString {

[key: string]: string;

}

const heroesInBooks: StringByString = {

'Gunslinger': 'The Dark Tower',

'Jack Torrance': 'The Shining'

};


The string type is the key, the value can be a string, number, or boolean:


interface Options {

[key: string]: string | number | boolean;

timeout: number;

}

const options: Options = {

timeout: 1000,

timeoutMessage: 'The request timed out!',

isFileUpload: false

};


Options interface also has a field timeout, which works fine near the index signature.

The key of the index signature can only be a string, number, or symbol. Other types are not allowed:


interface OopsDictionary {

// Type error:

// An index signature parameter type must be 'string', 'number',

// 'symbol', or a template literal type.

[key: boolean]: string;

}


3. Index signature caveats

The index signatures in TypeScript have a few caveats you should be aware of.

3.1 Non-existing properties

What would happen if you try to access a non-existing property of an object whose index signature is { [key: string]: string }?

As expected, TypeScript infers the type of the value to string. But if you check the runtime value — it's undefined:


interface StringByString {

[key: string]: string;

}

const object: StringByString = {};

const value = object['nonExistingProp'];

console.log(value); // => undefined


value variable is a string type according to TypeScript, however, its runtime value is undefined.

The index signature maps a key type to a value type — that's all. If you don't make that mapping correct, the value type can deviate from the actual runtime data type.

To make typing more accurate, mark the indexed value as string or undefined. Doing so, TypeScript becomes aware that the properties you access might not exist:


interface StringByString {

[key: string]: string | undefined;

}

const object: StringByString = {};

const value = object['nonExistingProp'];

console.log(value); // => undefined


3.2 String and number key

Let's say you have a dictionary of number names:


interface NumbersNames {

[key: string]: string

}

const names: NumbersNames = {

'1': 'one',

'2': 'two',

'3': 'three',

// etc...

};


Accessing a value by a string key works as expected:


const value1 = names['1']; // OK


Would it be an error if you access a value by a number 1?


const value2 = names[1]; // OK


Nope, all good!

JavaScript implicitly coerces numbers to strings when used as keys in property accessors (names[1] is the same as names['1']). TypeScript performs this coercion too.

You can think that [key: string] is the same as [key: string | number].

4. Index signature vs Record

TypeScript has a utility type Record<Keys, Values> to annotate records, similar to the index signature.


const object1: Record<string, string> = { prop: 'Value' }; // OK

const object2: { [key: string]: string } = { prop: 'Value' }; // OK


The big question is... when to use a Record<Keys, Values> and when an index signature? At first sight, they look quite similar!

As you saw earlier, the index signature accepts only string, number or symbol as key type. If you try to use, for example, a union of string literal types as keys in an index signature, it would be an error:


interface Salary {

// Type error:

// An index signature parameter type cannot be a literal type or generic type.

// Consider using a mapped object type instead.

[key: 'yearlySalary' | 'yearlyBonus']: number

}


This behavior suggests that the index signature is meant to be generic in regards to keys.

But you can use a union of string literals to describe the keys in a Record<Keys, Values>:


type SpecificSalary = Record<'yearlySalary'|'yearlyBonus', number>

type GenericSalary = Record<string, number>

const salary1: SpecificSalary = {

'yearlySalary': 120_000,

'yearlyBonus': 10_000

}; // OK


If you'd like to limit the keys to a union of specific strings, then Record<'prop1' | 'prop2' | ... | 'propN', Values> is the way to go instead of an index signature.

5. Conclusion

An index signature annotiation fits well the case when you don't know the exact structure of the object, but you know the key and value types.

The index signature consists of the index name and its type in square brackets, followed by a colon and the value type: { [indexName: Keys]: Values }. Keys can be a string, number, or symbol, while Values can be any type.

To limit the key type to a specific union of strings, then using the Record<Keys, Values> utilty type is a better idea. The index signature doesn't support unions of string literal types.

Check also my post about record type.

Do you prefer index signatures or Record<Keys, Values> utility type?