Having this specific interface structure:
interface test {
[key: string]: string
}
along with an object defined as follows:
const obj: test ={
name: 'mda',
telephone: '1234'
}
Attempting to utilize this object in a variable, the intellisense feature fails to function properly for this particular object. Essentially, it allows selecting a key that does not actually exist within the object.
const myName = obj.ndfnasdfn
No error is displayed by the compiler for such a key selection. You can access the playground area here: playground
An update involving a nested object: For this nested object scenario, what are the possible solutions? I implemented @Titian Cernicova-Dragomir's solution for the nested object mentioned below, however, no error is shown by the compiler.
interface test {
[key: string]: string
}
function createTest<T extends test>(o: T) {
return o;
}
interface state {
test1: test,
test2:test
}
const state: state = {
test1:createTest({
t1:'m',
t2:'e'
}),
test2: createTest({
t3:'sss'
})
}
const {test1, test2} = state
const t1 = test1.sdfsafsdf //no error
Further update: If we choose not to utilize the createTest function, and instead don't specify the type for the state object like demonstrated here playground
I proposed using types for the state object to prompt a compiler error for keys that do not exist in test1