0
0
Typescriptprogramming~5 mins

Indexed access types in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an indexed access type in TypeScript?
An indexed access type lets you look up the type of a property in another type using square brackets, like TypeName[Key]. It extracts the type of that property.
Click to reveal answer
beginner
How do you use indexed access types to get the type of a property 'name' from an interface Person?
You write Person['name']. This gives you the type of the 'name' property defined in Person.
Click to reveal answer
intermediate
Can indexed access types use union types as keys? Give an example.
Yes. For example, if key is 'name' | 'age', then Person[key] is the union of the types of name and age properties.
Click to reveal answer
intermediate
What happens if you use an indexed access type with a key that does not exist on the type?
TypeScript will give an error because the key is not assignable to the keys of the type. Indexed access types require valid keys.
Click to reveal answer
intermediate
Explain how indexed access types help with type safety in functions.
They let you write functions that accept keys of an object and return the exact type of the property at that key, ensuring you don't mix types accidentally.
Click to reveal answer
What does Person['age'] represent in TypeScript?
AThe value of the 'age' property in Person
BAn error because 'age' is a string
CA new object with only the 'age' property
DThe type of the 'age' property in Person
Can you use a union of keys in indexed access types like Person['name' | 'age']?
AYes, it returns a union of the property types
BNo, it causes a syntax error
CYes, but only if the keys are numbers
DNo, it returns the first key's type only
What error occurs if you use an invalid key in an indexed access type?
ANo error, it returns <code>any</code>
BType error: key not assignable to keys of the type
CRuntime error
DSyntax error
Which of these is a valid use of indexed access types?
Atype AgeType = Person['age'];
Blet age: Person['age'] = 'twenty';
CPerson['height'] = 180;
Dtype Name = Person.name;
How do indexed access types improve function definitions?
ABy allowing functions to ignore types
BBy making functions run faster
CBy allowing functions to return the exact property type based on a key parameter
DBy converting all types to strings
Describe what indexed access types are and how they are used in TypeScript.
Think about how you get a property type from an object type.
You got /3 concepts.
    Explain how indexed access types can help make your TypeScript code safer when working with object properties.
    Consider how knowing exact property types prevents errors.
    You got /3 concepts.