Home > Enterprise >  How can I get Typescript to understand what the value type of a homogenous object is without losing
How can I get Typescript to understand what the value type of a homogenous object is without losing

Time:03-03

How can I get Typescript to understand what the value type of an object is without losing access to the key information from its static declaration?

In the below code I want the benefit of

  • TS knowing the type of the value, in this case a function so I don't have to specify it's signature every time.
  • TS knowing the keys of the object from static declaration so I can reference them in a type safe fashion from elsewhere

This object is homogenous and will have lots of functions, specifying the signature every time seems like a pain.

Example 1 - TS doesn't know the keys of the object

    interface Foo {
        [key: string]: (n: number) => any
    }
    
    const obj1: Foo = {
        // TS already knows that `n` is a number            
  • Related