-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Extending the Function interface in the presence of an import statement #5944
Comments
In the TypeScript spec section 11.3 it states
In your original working version, there are no import or export declarations, so the things you've declared there are in the global namespace. So you've told When you introduce the The final line |
As per your 'Note2' you want to monkey-patch built-in objects, which is frowned on if it can be avoided. Having said that, TypeScript can model monkey-patching just fine if you must do it. Just declare the additions to the built-ins ambiently in a .d.ts file. Any TypeScript project using your library would need to include that .d.ts file in its own build to pick up the patched types. E.g.: // file: monkey.d.ts
interface Function {
hello(): any
}
// file: monkey.ts
///<reference path="monkey.d.ts" />
export function patch() {
Function.prototype.hello = function() {
console.log('hello world')
}
}
// file: example.ts
///<reference path="monkey.d.ts" />
import monkey = require('./monkey');
monkey.patch();
function noop() {}
noop.hello() // OK: should pick up 'hello' member declared in monkey.d.ts Hopefully you can see the pitfalls of doing this (eg what if you forget to call |
See also #4166 |
@yortus Great answer. Thanks. So, unfortunately there is no way to "export" augmentation to the existing interfaces from a library. I understand the dangers of monkey patching but still see this as unfortunate: I come from the Scala world where there is a way to "pimp" existing types without having to resort to monkey patching. |
Agreed. It's trivial to do in JavaScript, so it would be good to be able to model it just as easily in TypeScript. |
I would like to extend
Function
and this compiles fineHowever, as soon as I try to add an import statement, say
where
Anything
only containsThe compilation fails on
Function.protoype.hello
with the messageerror TS2339: Property 'hello' does not exist on type 'Function'
Why ?
View in Playground
Note1: the compilation fails with tsc options set to either
--target es5 --module commonjs
or--target es6
Note2: my final goal is to export utilities in a library to be able to write code like
myfunc.liftM(myMonad1, MyMonad2)
ormyfunc1.compose(myfunc2)
, etc...The text was updated successfully, but these errors were encountered: