0
0
Typescriptprogramming~5 mins

Index signatures for dynamic keys in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an index signature in TypeScript?
An index signature allows you to define the type of keys and values for objects with dynamic keys, meaning keys that are not known in advance.
Click to reveal answer
beginner
How do you declare an index signature for an object with string keys and number values?
You write: { [key: string]: number } which means any string key maps to a number value.
Click to reveal answer
intermediate
Can index signatures use types other than string for keys?
Yes, index signatures can use string or number as key types, but not other types like boolean.
Click to reveal answer
intermediate
What happens if you mix explicit properties and an index signature in a TypeScript interface?
Explicit properties must have types compatible with the index signature's value type, otherwise TypeScript will show an error.
Click to reveal answer
beginner
Why are index signatures useful in real-life programming?
They let you work with objects where keys are not fixed, like dictionaries or maps, making your code flexible and type-safe.
Click to reveal answer
Which syntax correctly declares an index signature for an object with string keys and boolean values?
A{ key: string; value: boolean }
B{ [key: boolean]: string }
C{ [key: number]: boolean }
D{ [key: string]: boolean }
What type can NOT be used as an index signature key in TypeScript?
Aboolean
Bnumber
Cstring
Dall of the above can be used
If an interface has an index signature { [key: string]: number }, what type must explicit properties have?
Astring
Bnumber
Cany
Dboolean
What does this index signature mean? { [id: number]: string }
AKeys are numbers, values are strings
BKeys are strings, values are numbers
CKeys and values are both numbers
DKeys and values are both strings
Why use index signatures instead of fixed property names?
ATo restrict keys to a fixed set
BTo make code slower
CTo allow objects with unknown or dynamic keys
DTo avoid using types
Explain what an index signature is and how it helps with dynamic keys in TypeScript.
Think about objects where keys are not fixed but you still want to know the type of values.
You got /3 concepts.
    Describe the rules for mixing explicit properties and index signatures in a TypeScript interface.
    Consider what happens if explicit property types don't match the index signature type.
    You got /3 concepts.