Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is a TypeScript index signature

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

The main content of this article is to explain "what is TypeScript index signature". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the TypeScript index signature"?

Catalogue

1. What is an index signature?

two。 Index signature syntax

3. Considerations for indexed signatures

3.1 attributes that do not exist

3.2 string and number keys

4. Comparison between indexed signature and Record

We use two objects to describe the salaries of two programmers:

Const salary1 = {baseSalary: 100000, yearlyBonus: 20000}; const salary2 = {contractSalary: 110000}

Then write a function to get the total salary.

Function totalSalary (salaryObject:?) {let total = 0; for (const name in salaryObject) {total + = salaryObject [name];} return total;} totalSalary (salary1); / / = > 120_000totalSalary (salary2); / / = > 11000000

If it is yours, how do you declare the salaryObject parameter of the totalSalary () function to accept objects with string keys and numeric values?

The answer is to use an index signature!

Next, let's take a look at what TypeScript index signatures are and when they are needed.

1. What is an index signature?

The idea of index signature is to classify objects whose structures are unknown when only the key and value types are known.

It exactly matches the case of the salary parameter, because the function should accept salary objects of different structures, and the only requirement is that the attribute value is a number.

We declare 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;} totalSalary (salary1); / / = > 120_000totalSalary (salary2); / / = > 11000000

{[key: string]: number} is an index signature that tells TypeScript salaryObject that it must be an object with a key of type string and a value of type number.

two。 Index signature syntax

The syntax of an index signature is quite simple and looks similar to the syntax of attributes, but with one difference. We just need to write the type of key in square brackets instead of the attribute name: {[key: KeyType]: ValueType}.

Here are some examples of index signatures.

String types are keys and values.

Interface StringByString {[key: string]: string;} const heroesInBooks: StringByString = {'Gunslinger':' front-end Xiao Zhi', 'Jack Torrance':' Wang Dazhi'}

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 outflows, isFileUpload: false}

The signed key can only be a string`, number, or symbolic. Other types are not allowed.

3. Considerations for indexed signatures

Index signatures in TypeScript have some considerations that need to be noted.

3.1 attributes that do not exist

What happens if you try to access a nonexistent property of an object with an index signature of {[key: string]: string}?

As expected, TypeScript infers the type of the value as string. But check the runtime value, which is undefined:

According to the TypeScript prompt, the value variable is of type string, but its runtime value is undefined.

Index signatures simply map a key type to a value type, that's all. If this mapping is not made correct, the value type may 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 will realize that the property you are accessing may not exist

3.2 string and number keys

Suppose you have a dictionary of numeric names:

Interface NumbersNames {[key: string]: string} const names: NumbersNames = {'1percent:' one', '2percent:' two', '3percent:' three', / /...}

No, it's working normally.

When used as a key in a property accessor, JavaScript implicitly forces numbers into strings (names [1] is the same as names ['1']). TypeScript also enforces this enforcement.

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

4. Comparison between indexed signature and Record

TypeScript has a utility type Record, which is similar to an index signature.

Const object1: Record = {prop: 'Value'}; / / OKconst object2: {[key: string]: string} = {prop:' Value'}; / / OK

That's the problem. When to use Record and when to use indexed signatures? At first glance, they look very similar

We know that index signatures only accept string, number, or symbol as key types. If you try to use a union of literal types of strings as keys in indexed signatures, for example, this is an error.

Index signatures are universal in terms of keys.

But we can use a union of string literals to describe keys in Record

Type Salary = Record const salary1: Salary = {'yearlySalary': 12000000,' yearlyBonus': 10000}; / / OK

Record is designed to be specific to key issues.

It is recommended that you use an index signature to annotate a generic object, for example, the key is a string type. However, when you know the key in advance, use Record to annotate specific objects, such as the literal string 'prop1' |' prop2' is used for key values.

Summary:

If you don't know the object structure you're dealing with, but you know the possible key and value types, then the index signature is what you need.

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

At this point, I believe you have a deeper understanding of "what is an TypeScript index signature". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report