Typescript TS7053
It is quick memo to fix TS7053 error, it took a while to fix it on other day. Here is a example code.
interface PointCondition {
pleasurePoint: number;
steamerLane: number;
};
const state: PointCondition = {
pleasurePoint: 88,
steamerLane: 92,
};
function getCondition(key: string) : number {
return state[key];
};
Object.keys(state).forEach(function(key){
return console.log( getCondition(key) );
})
"strict": true
in tsconfig.json
If you try to compile this example code with tsc
command, you get
- error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'PointCondition'.
No index signature with a parameter of type 'string' was found on type 'PointCondition'.
How to fix TS7053
When I first saw this, I specify key: string
for the argument, why do I a get error?
I did online search and couple of tests and found out I need to limit strings of key.
return state[key as keyof PointCondition ];
Here is compilable code.
interface PointCondition {
pleasurePoint: number;
steamerLane: number;
};
const state: PointCondition = {
pleasurePoint: 88,
steamerLane: 92,
};
function getCondition(key: string) : number {
return state[key as keyof PointCondition ];
};
Object.keys(state).forEach(function(key){
return console.log( getCondition(key) );
})