This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
By Dmitri Pavlutin
Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom.
In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.
We use two objects to describe the wages of two code farmers:
const salary1 = {
baseSalary: 100_000,
yearlyBonus: 20_000
};
const salary2 = {
contractSalary: 110_000
};
Copy the code
And then write a function that gets the total wage
function totalSalary(salaryObject: ???) { let total = 0; for (const name in salaryObject) { total += salaryObject[name]; } return total; } totalSalary(salary1); // => 120_000 totalSalary(salary2); / / = > 110 _000Copy the code
If yours, how do YOU declare the salaryObject argument to the totalSalary() function to accept objects with string keys and numeric values?
The answer is to use an index signature!
Next, let’s look at what TypeScript index signatures are and when they are needed.
1. What is index signature
The idea of index signature is to classify objects whose structure is unknown when only the key and value types are known.
This is exactly what happens with the Salary argument, because the function should accept a salary object of different structures, the only requirement being that the attribute value be a number.
We declare the salaryObject parameter with the index signature
function totalSalary(salaryObject: { [key: string]: number }) { let total = 0; for (const name in salaryObject) { total += salaryObject[name]; } return total; } totalSalary(salary1); // => 120_000 totalSalary(salary2); / / = > 110 _000Copy the code
{[key: String]: number} is an index signature that tells TypeScript salaryObject must be an object with a string key and a number value.
2. Index signature syntax
The syntax for index signatures is fairly simple and looks similar to the syntax for attributes, with one difference. We simply write the type of the key in square brackets instead of the attribute name: {[key: KeyType]: ValueType}.
Here are some examples of index signatures.
Strings are keys and values.
interface StringByString { [key: string]: string; } const heroesInBooks: StringByString = {'Gunslinger': 'Jack Torrance': 'Wang Dachi'};Copy the code
The string type is a key, and the value can be 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 };Copy the code
The signed key can only be a string, number, or symbol. Other types are not allowed.
3. Precautions for index signatures
There are a few caveats to index signatures in TypeScript.
3.1 Non-existent attributes
What happens if you try to access a nonexistent property of an object whose index signature is {[key: string]: string}?
As expected, TypeScript extrapolates the type of a value to string. But check the runtime value, which is undefined:
As TypeScript prompts, the value variable is a string, but its runtime value is undefined.
Index signatures simply map a key type to a value type, nothing more. If this mapping is not done correctly, the value type can deviate from the actual runtime data type.
To make the input more accurate, mark the index value as string or undefined. In this way, TypeScript realizes that the property you’re accessing may not exist
3.2 String and Number keys
Suppose there is a dictionary with numeric names:
interface NumbersNames {
[key: string]: string
}
const names: NumbersNames = {
'1': 'one',
'2': 'two',
'3': 'three',
// ...
};
Copy the code
Values accessed through string keys are as expected:
Can I get an error if I access a value with the number 1?
No, it works fine.
JavaScript implicitly enforces numbers as strings when used as keys in property accessors (names[1] is the same as names[‘1’]). TypeScript does this as well.
You can think [key: string] and [key: string | number].
4. Index signature andRecord<Keys, Type>
contrast
TypeScript has a utility Type Record
, similar to index signatures.
const object1: Record<string, string> = { prop: 'Value' }; // OK
const object2: { [key: string]: string } = { prop: 'Value' }; // OK
Copy the code
Here’s the problem… When to use Record
and when to use index signatures? At first glance, they look very similar
As we know, index signatures only accept string, number, or Symbol as key types. If you try to use, for example, a union of string literal types as a key in an index signature, this is an error.
Index signatures are generic in terms of keys.
But we can use a union of string literals to describe the keys in Record
type Salary = Record<'yearlySalary'|'yearlyBonus', number>
const salary1: Salary = {
'yearlySalary': 120_000,
'yearlyBonus': 10_000
}; // OK
Copy the code
Record
is for key-specific problems.
It is recommended to use index signatures to annotate generic objects, for example, where keys are strings. But, when you know in advance, to use Record < Keys, Type > annotation for a particular object, such as a string literal ‘prop1’ | ‘prop2’ is used in the key values.
conclusion
If you don’t know the structure of the object you’re dealing with, but you know the possible key and value types, then index signatures are what you need.
The index signature consists of the indexName and its type enclosed in square brackets, followed by a colon and value type: {[indexName: KeyType]: ValueType}, KeyType can be a string, number, or symbol, and ValueType can be any type.
Finish, I am brush bowl wisdom, write this one piece king newest picture “tianwang mountain” updated super stimulation, I want to chase, we see next period!
Please feel free to discuss in the comments section. The nuggets will draw 100 nuggets in the comments section after the diggnation project. See the event article for details
The possible bugs in editing can not be known in real time. In order to solve these bugs after the event, I spent a lot of time on log debugging. By the way, I recommend a good bug monitoring tool for youFundebug.
Original text: dmitripavutin.com/typescript-…