A
A
Andrey Suha2020-05-25 09:48:50
typescript
Andrey Suha, 2020-05-25 09:48:50

How to set types for dynamic properties of an object?

Hello!

There is such a function

render(element: string, args: RenderArgs = {}, pos: Pos = Pos.end): void {
        for (let key in args) {
            element = element.replace(new RegExp(`{{${key}}}`), args[key]);
        }
        this.mountElement.insertAdjacentHTML(pos, element);
    }


trying to set args like this

export type RenderArgs = { [ key: string ]: number | string }


those. args is an object whose properties can only be numbers or strings

but I get this error

ZyeW3jc.png

How to solve this?

Ps do not throw stones, please, this is the first experience with typescript, if I misunderstood something, please indicate what I need to calculate

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Suha, 2020-05-25
@andreysuha

The problem was in this line

element = element.replace(new RegExp(`{{${key}}}`), args[key]);

replace expects a string as second parameter, f args[key] can be either string or number Decide to cast args[key] to a string

N
Noir, 2020-05-25
@PolarBearGG

any

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question