Index signature and keyof operator in Typescript
Meet Vaghasiya
Passionate Vue.js & Laravel Developer | JavaScript Lover | Eager to Learn
Let's say we have two types of objects. and you want to make a common function that returns total marks
Here we have two different types of objects
?{ [key: string]: number }, where we are telling typescript that object with all key type is string and value is number is valid. Here word key does not matter, we can use any word instead of the key. like { [index: string]: number } .
we also make a type for this and use it as below
In the above, MarkIndex2 is not valid. because [key: string]: number is telling typescript that all property has number type of value. so we can not give other types. however, if we want to use multiple types we make a union for this.
We can also define nested properties for objects
领英推荐
Index signature caveats
[key: string] : number
[key: number] : number
[key: symbol] : number
[key: boolean] : number //Error
Suppose you have a user object and you want to return a value based on the key. so we need to restrict the value of the key based on object property. in the below example, key is invalid still typescript will not throw an error.
So keyof operator is used in this type of scenario.
now only the name and age property are valid.