Consider the following TypeScript interface and object:
interface Scores {
[player: string]: number;
}
const gameScores: Scores = {
alice: 10,
bob: 15
};
console.log(gameScores['alice']);
console.log(gameScores['charlie']);What will be printed to the console?
interface Scores {
[player: string]: number;
}
const gameScores: Scores = {
alice: 10,
bob: 15
};
console.log(gameScores['alice']);
console.log(gameScores['charlie']);Think about what happens when you access a key that does not exist in an object.
The index signature allows any string key with a number value. Accessing 'alice' returns 10. Accessing 'charlie' returns undefined because that key is not set.
Choose the correct TypeScript syntax for an interface that allows any string key with a string value.
Index signatures require a type for the key inside square brackets.
Option D correctly uses [key: string] to declare an index signature for string keys with string values.
Given this interface and object:
interface Config {
[key: string]: number;
port: number;
}
const serverConfig: Config = {
port: 8080,
host: 'localhost'
};Why does this code cause a TypeScript error?
Check the types of all properties against the index signature type.
The index signature says all keys must have number values. 'host' has a string value, so it violates the index signature.
You want an interface that allows any string key with either a string or number value. Which is the best way to declare it?
Consider union types for values in index signatures.
Option B uses a union type (string | number) which allows values to be either string or number for any key.
Which statement best describes a limitation when using index signatures for dynamic keys?
Think about how explicit properties relate to the index signature type.
When an interface has an index signature, all explicitly declared properties must have values compatible with the index signature's value type.