1

I have a TypeScript object that contains both a known static key and an unknown number of dynamic keys. At a given point in time the object can look like this:

{
    created: 32323232,
    'https://gbhgr.com/bhtgttg/bffgth': <Observable1>,
    'https://trhhhtgrhgr.com/bgbtebg/byrf': <Observable2>,
    'https://domain4.com/ngfbgb/frogf': <Observable4>
}

I can't figure out how to type this. The type I came up with:

type Cache = {
  created: number,
  [key:string]?: Observable<HttpResponse<any>>
}

gives Typescript errors on the line

 [key:string]?: Observable<HttpResponse<any>>

on ? (there can be 0,n number of keys so it's optional, therefore the ?):

';' expected.ts(1005)
Property or signature expected.ts(1131)

on Observable:

(method) Observable<HttpResponse>(): any
'Observable', which lacks return-type annotation, implicitly has an 'any' return type.ts(7010)

on HttpResponse:

(type parameter) HttpResponse in Observable<HttpResponse>(): any
'HttpResponse' is declared but its value is never read.ts(6133)
'Observable', which lacks return-type annotation, implicitly has an 'any' return type.ts(7010)

on any:

(type parameter) any in <any>(): any
'any' is declared but its value is never read.ts(6133)
Call signature, which lacks return-type annotation, implicitly has an 'any' return type.ts(7020)
Type parameter name cannot be 'any'.ts(2368)

What do the errors mean? How can I do this?

typescript version: "~4.3.2"

Marc
  • 401
  • 1
  • 5
  • 15
  • 1
    Your code has a bunch of errors and it's not clear that it makes sense for an answer to go through each one. You don't need (and can't write) a `?` on an [index signature](https://www.typescriptlang.org/docs/handbook/2/objects.html#index-signatures); they already accept any number of keys including zero. The other errors probably clear up once you remove the `?`. Your fundamental problem is going to be that you cannot have the dynamic props be one type and the static props be of an incompatible type. – jcalz Feb 04 '22 at 16:55
  • 1
    If you update your TS version you can use a template literal pattern index signature so that any key that starts with `"http"` will be of the `Observable>` type you want and `created` will be a `number`, like [this maybe](https://tsplay.dev/w16EkN) (but it's important for your question code to include a [mre] with no external dependencies you don't have as tags). – jcalz Feb 04 '22 at 17:04
  • 1
    ... so my type should be type Cache = { [key:string]: Observable> | number } saying 'this type accepts any key with a return value of Observer or a number...' – Marc Feb 04 '22 at 17:05
  • 1
    @jcalz '...you cannot have the dynamic props be one type and the static props be of an incompatible type.'. Didn't know that. Thanx for pointing out the (obvious) ? error and the example. – Marc Feb 04 '22 at 17:18
  • Yes, the union is one way of doing that. For that and other approaches, see the answer to the linked question. – jcalz Feb 04 '22 at 17:20

0 Answers0