0

I'm trying to create a Typescript class that has unknown property names with known values as well as methods. I don't have any problem with the unknown property names but when I try to add a method I get an error: "Property 'update' of type '() => void' is not assignable to 'string' index type 'Quote'."

EDIT: adding data info Data would look like (I know the symbol is redundant but it just has to be that way):

{
'TQQQ': {
        symbol: 'TQQQ',
        lastPrice: 50
        }
}
interface Quote {...}

class Watchlist {
    [key: string]: Quote
    update() {...}
}

Here's a playground

6
  • What if you index into it with update? Then it'd be a function, not a Quote. Commented Nov 7, 2022 at 1:35
  • Maybe you need something like this if your keys will have some sort of pattern to them. Commented Nov 7, 2022 at 1:36
  • They won't have any pattern. I need to have the data and methods all within the class. I guess I could put the data into another property but it'll cause a lot of extra typing. Seems there should be a way to add a method to this class. The class works fine until I try to add the method. Commented Nov 7, 2022 at 1:44
  • Also I should mention if I use @ts-ignore everything works exactly as it should. I just hate doing that. Commented Nov 7, 2022 at 1:46
  • You should definitely be using another property to hold all of this. Commented Nov 7, 2022 at 2:03

1 Answer 1

1

It is unclear to me why would you need a class with endless unknown properties. It will not be handy. Consider adding a property like "quotes" where you store an object with all the quotes as [key:string]: Quote

Playground

Sign up to request clarification or add additional context in comments.

1 Comment

The reason is when I receive this data from an outside source it is structured the way I describe in my original post. The property names are stock symbols, which could be any of thousands. I see I will likely have to contain them all into another property name or just use @ts-ignore (probably the latter). Thank you.

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.