0

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

1
  • sorry revised code Commented Apr 2, 2021 at 5:46

1 Answer 1

2

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,
}
Sign up to request clarification or add additional context in comments.

1 Comment

When an answer solves your problem, you can consider marking it as Accepted (check the checkbox on the left) to indicate that the issue is resolved :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.