Reputation: 315
I have a node buffer
const meter = {
readFunction: 'readUIntLE',
}
const buf = Buffer.from('01590D000022B65160010044BC1F000003036801', 'hex')
const method = meter.readFunction
I want to execute buf[method](0,1)
but typescript warns me with an error
Element implicitly has an 'any' type because index expression is not of type 'number'
Eval doesn't look good to execute, but I am not too sure how to get rid or an error by other means
Upvotes: 0
Views: 113
Reputation: 370729
The problem is that your object is typed as
readFunction: string
and not
readFunction: 'readUIntLE'
so TS doesn't see that the buf[method]
refers to the method you want - it just sees an arbitrary string, which could be anything.
Declare the object as const
to avoid the problematic widening.
const meter = {
readFunction: 'readUIntLE' as const,
}
Upvotes: 2