Nikhil Yeole
Nikhil Yeole

Reputation: 347

How to preserve type definitions of a function while exposing it on global namespace (object)?

Basically I don't want to import lodash functions is each file. I want to expose them on some global namespace(e.g. L). I don't want to import whole of lodash library but only import few functions. I am trying following things but then I loose type support.

interface Lod {
  head: Function
}

interface Window {
  L: Lod;
}

import head = require('lodash/head');

window.L = {
  head: head
}

So now when I use head() then IDE gives me intellisense support (showing errors as no argument is passed but I should give an array) and also i get compilation errors from typescript saying I am passing incorrect parameters to head (which is correct).

But when I use window.L.head() then I don't get any help from intellisense(no errors) and typescript also don't give any error at compilation (which is wrong, I should get errors).

Thanks a lot for your help in advance!

Upvotes: 0

Views: 68

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164417

When you use head directly the compiler can check the definitions in it which is why the intellisense work and you're getting errors.

But your definition of Lod.head is a Function, which is why the compiler is fine with you passing whatever arguments.

You should do this:

import head = require('lodash/head');

interface Lod {
    head: typeof head
}

Upvotes: 1

Related Questions