I am a noob in working with typescript, but cannot avoid it in angular. So, I was writing the code as I learn.
I wanted to make a function that iterates over the keys of an object and performs some small tasks. In my case, I want to iterate through the keys because interface properties are optional and all of them may not be present. Here is the relevant part of my code: -
interface GameState {
gameId?: string,
minPlayers?: number,
currentChoiceMakingPlayer?: number,
gameEndReason?: string,
}
export class GameManagerService {
gameState: GameState = {};
synchroniseGameData = (gameState: GameState) => {
for (let key in Object.keys(gameState)) {
let typeKey = <keyof GameState>key;
this.updateEntryInGameState(typeKey, gameState[typeKey]);
}
};
updateEntryInGameState = <GameStateKey extends keyof GameState>(key: GameStateKey, value: GameState[GameStateKey]) => {
this.gameState[key] = value;
};
}
I understand most of it, except for the actual spotlight stealer function updateEntryInGameState (bottom of the code).
The tutorial I used gave this brief explanation (which I'll translate with respect to parameter names in my code): -
Adding the type variable
GameStateKeyfor thekeytype allows us to use it for thevaluetype while still ensuring that thekeyis a key of GameState usingextends keyof GameState
But I still don't fully understand how this works.
Mainly, What does <GameStateKey extends keyof GameState> do before the function definition? And how is it being applied to the parameters of the function?