Han Che
Han Che

Reputation: 8509

How to instantiate an interface with an empty object?

export interface MapObj {
  (s: string): TaskDaylist
}

let map: MapObj = {};

and I get a type error

Type '{}' is not assignable to type '(s: string) => TaskDaylist'. Type '{}' provides no match for the signature '(s: string): TaskDaylist'.

I can't make it optional with ?:

  (s: string)?: TaskDaylist

Is there another way that I can type the map and instantiate it with an empty object?

Upvotes: 1

Views: 1656

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164129

You can use type assertion for that:

let map: MapObj = {} as MapObj;

Or simply:

let map = {} as MapObj;

(code in playground)


Edit

The type you have for MapObj is a type for a function, so something like this:

let map: MapObj = function (s: string) {
    return {};
};

If you just want an object which maps between strings (key) to TaskDaylist (values), then it should look like this:

interface MapObj {
    [s: string]: TaskDaylist;
}

More about it in Indexable Types.

Upvotes: 2

Related Questions