I was trying to be a sneaky developer, and I done got myself lost in ES6 Proxies. Basically I wanted to capture any get or set in a property from another class I wrote and make sure they are stored somewhere else besides the object. It looks like this:
'use strict'
class MyObject()
{
superAwesomeFunction(){//super awesome code goes here}
}
const myProxyObject = new Proxy(MyObject, {
get: function(target, name, receiver)
{
if([CONDITIONS THAT MEET MY DEMANDS])
{
// deliver property values if they are
// my super cool database (if they exist)
}
// else just ya know, forward it to the actual MyObject
// property, if it's an actual property on MyObject
return target[name];
},
set: function(target, name, value)
{
if([CONDITIONS THAT MEET MY DEMANDS])
{
// set property values if they are
// to super cool database
}
else
{
// just set the value to the property, which
// gets created if it doesn't exist (WHICH IS SO COOL)
target[name] = value;
}
return true;
}
Okay the cool part about this? you can do something like:
// property that doesn't exist (yet)
console.log(myProxyObject.wholivesinapineappleunderthesea);
// but wait for it...
myProxyObject.wholivesinapineappleunderthesea = 'spongebob';
// bam! now it exists on the object, AND lives in my DB!
console.log(myProxyObject.wholivesinapineappleunderthesea);
Which, while a lot of work for something dorky, i cannot explain how happy it makes me feel. However, there is a problem with this. Remember that superAwesomeFunction() I put in MyObject()? Well whenever I try to call it now ES6 gives me this load of sadness:
myProxyObject.superAwesomeFunction is not a function
ES6 sits on a throne of LIES! It's totally there right? Okay so I'm pretty sure I'm trapping something wrong, because when I debug I see that the get section of the Proxy is actually picking up the superAwesomeFunction call (which makes sense as superAwesomeFunction is a property that contains a function (){})
HERE'S MY QUESTION: Does anybody know of any solution that will let me keep my ridiculous on the fly properties and still call my superAwesomeFunction()? Is it the apply trap?
To extend on Sam's answer.
The following succeeds:
function Foo() {
this.bar = function() { console.log('baz'); }
}
let foo = new Proxy(new Foo(), {});
foo.bar();
However, when the get trap is added to the handler, "is not a function" is thrown:
function Foo() {
this.bar = function() { console.log('baz'); }
}
let foo = new Proxy(new Foo(), {
get: function(target, prop) {}
});
foo.bar();
The solution here is to add a typeof check for default handling of the target's existing functions:
function Foo() {
this.bar = function() { console.log('baz'); }
}
let foo = new Proxy(new Foo(), {
get: function(target, prop) {
if (typeof target[prop] === 'function') {
return target[prop].bind(target);
}
}
});
foo.bar();
The following articles gives some more examples and provides nice boilerplate to use with Proxy handlers: Safely Extending The JavaScript Set Object Using Proxies
It is a little syntax error there ... you are wrapping the proxy around the raw class, not an object.
Try:
const myProxyObject = new Proxy(new MyObject(), { ... });
This should be ok. For example:
> class Blah {
... run() {
..... console.log('yay')
..... }
... }
[Function: blah]
> myProx = new Proxy(new Blah(), {});
blah {}
> myProx.run()
yay
Full code for answer is here, thank you everyone!
'use strict'
class MyObject()
{
superAwesomeFunction(){
console.log("this works!");
}
}
const myProxyObject = new Proxy( new MyObject(), {
get: function(target, name, receiver)
{
if([CONDITIONS THAT MEET MY DEMANDS])
{
// do something cool for yourself
}
return target[name];
},
set: function(target, name, value)
{
if([CONDITIONS THAT MEET MY DEMANDS])
{
// do something cool for yourself
}
else
{
// just set the value to the property, which
// gets created if it doesn't exist (WHICH IS SO COOL)
target[name] = value;
}
return true;
}
});
Related
This is a purely theoretical question here (though one I think is an interesting thought exercise). I was just working on a JavaScript object (documentation-related) and the somewhat-unusual thought crosses my mind: is there a way to make a key/value pair entry within said object capable of reading its own key as part of its value? That is to say:
Assuming I have a JavaScript object used for the purposes of serializing data:
{
"someKey":()=>"M-me? MY key is '" + voodoo(this) + "'! Thanks so much for taking an interest!"
}
...is there a way I can get "M-me? MY key is 'someKey'! Thanks so much for taking an interest!" as an (albeit: rather asinine) output when addressing the key? I totally don't care what the structure would look like, nor what the type of the Value of the portion of the KVP would be, NOR what arguments would need passed it (if any? I'm just assuming it would have to be a function, after all).
I mean, of course it's possible; it's code. It's ALL possible (I've seen a quine that can ascertain its own SHA-512 hash, for heaven sake). But I find it to be an interesting thought experiment, and wanted to see if anyone already had some Code Kung Fu/Source Santeria (even at the abstract/pseudo-code level) and/or someone that might have some ideas.
I've tinkered with going so far as to actually parse the JavaScript source file line-by-line and test for the remainder of the output string to place it (worked, but lame... What if it's a constructed object?), then thought of stringifying it and RegEx-ing it out (worked, but still pretty weak... Relies too much on advance knowledge of what would have to be an unchanging structure).
I'm now fiddling with attempting to filter the object on and by itself to try and isolate the key making the request, which I expect will work (-ish), but still leaves me feeling kind of like the bull in a china shop. I can extend the Object prototype (I know, I know. Theoretical, remember?) so the self-reference doesn't pose a problem, but I'm stumped as to providing a means for the KVP to identify itself uniquely without having to search for some set portion of string.
Anyone have any thoughts? No holds barred: this will probably never see the light of a production environment - just an interesting puzzle - so feel free to muck with prototypes, include libraries, fail to indent... whatever*. Frankly, it doesn't really even have to be in JavaScript; that's just what I'M using. It's 2:30am here, and I'm just noodling on if it's DOABLE.
* (Please don't fail to indent. Twitch-twitch (ಥ∻.⊙) It seems I lied about that part.)
Reflexively lookup the key on call
This is probably the most surefire way to do it. When obj.foo() is called, then foo is executed with obj set as the value of this. This means that we can lookup the key from this. We can examine the object easily the hardest thing is to find which key contains the function we just executed. We can try to do string matching but it might fail for:
const obj = {
foo: function() { /* magic */ },
bar: function() { /* magic */ },
}
Because the contents of the functions will be the same but the keys are different, so it's not easy to differentiate between obj.foo() and obj.bar() by doing string matching.
However, there is a better option - naming the function:
const obj = {
foo: function lookUpMyOwnKey() { /* magic */ }
}
Normally, there is pretty much no effect whether you give the function a name or not. However, the thing that we can leverage is that the function can now refer to itself by the name. This gives us a fairly straightforward solution using Object.entries:
"use strict";
const fn = function lookUpMyOwnName() {
if (typeof this !== "object" || this === null) { //in case the context is removed
return "Sorry, I don't know";
}
const pair = Object.entries(this)
.find(([, value]) => value === lookUpMyOwnName);
if (!pair) {
return "I can't seem to find out";
}
return `My name is: ${pair[0]}`
}
const obj = {
foo: fn
}
console.log(obj.foo());
console.log(obj.foo.call(null));
console.log(obj.foo.call("some string"));
console.log(obj.foo.call({
other: "object"
}));
This is pretty close to the perfect solution. As we can see, it even works if the function is not defined as part of the object but added later. So, it's completely divorced from what object it's part of. The problem is that it's still one function and adding it multiple times will not get the correct result:
"use strict";
const fn = function lookUpMyOwnName() {
if (typeof this !== "object" || this === null) { //in case the context is removed
return "Sorry, I don't know";
}
const pair = Object.entries(this)
.find(([, value]) => value === lookUpMyOwnName);
if (!pair) {
return "I can't seem to find out";
}
return `My name is: ${pair[0]}`
}
const obj = {
foo: fn,
bar: fn
}
console.log(obj.foo()); // foo
console.log(obj.bar()); // foo...oops
Luckily, that's easily solvable by having a higher order function and creating lookUpMyOwnName on the fly. This way different instances are not going to recognise each other:
"use strict";
const makeFn = () => function lookUpMyOwnName() {
// ^^^^^^ ^^^^^
if (typeof this !== "object" || this === null) { //in case the context is removed
return "Sorry, I don't know";
}
const pair = Object.entries(this)
.find(([, value]) => value === lookUpMyOwnName);
if (!pair) {
return "I can't seem to find out";
}
return `My name is: ${pair[0]}`
}
const obj = {
foo: makeFn(),
bar: makeFn()
}
console.log(obj.foo()); // foo
console.log(obj.bar()); // bar
Making really sure we find the key
There are still ways this could fail
If the call comes from the prototype chain
If the property is non-enumerable
Example:
"use strict";
const makeFn = () => function lookUpMyOwnName() {
// ^^^^^^ ^^^^^
if (typeof this !== "object" || this === null) { //in case the context is removed
return "Sorry, I don't know";
}
const pair = Object.entries(this)
.find(([, value]) => value === lookUpMyOwnName);
if (!pair) {
return "I can't seem to find out";
}
return `My name is: ${pair[0]}`
}
const obj = {
foo: makeFn()
}
const obj2 = Object.create(obj);
console.log(obj.foo()); // foo
console.log(obj2.foo()); // unknown
const obj3 = Object.defineProperties({}, {
foo: {
value: makeFn(),
enumerable: true
},
bar: {
value: makeFn(),
enumerable: false
}
})
console.log(obj3.foo()); // foo
console.log(obj3.bar()); // unknown
Is it worth making an overengineered solution that solves a non-existing problem just to find everything here?
Well, I don't know the answer to that. I'll make it anyway - here is a function that thoroughly checks its host object and its prototype chain via Object.getOwnPropertyDescriptors to find where exactly it was called from:
"use strict";
const makeFn = () => function lookUpMyOwnName() {
if (typeof this !== "object" || this === null) {
return "Sorry, I don't know";
}
const pair = Object.entries(Object.getOwnPropertyDescriptors(this))
.find(([propName]) => this[propName] === lookUpMyOwnName);
if (!pair) {//we must go DEEPER!
return lookUpMyOwnName.call(Object.getPrototypeOf(this));
}
return `My name is: ${pair[0]}`;
}
const obj = {
foo: makeFn()
}
const obj2 = Object.create(obj);
console.log(obj.foo()); // foo
console.log(obj2.foo()); // foo
const obj3 = Object.defineProperties({}, {
foo: {
value: makeFn(),
enumerable: true
},
bar: {
value: makeFn(),
enumerable: false
},
baz: {
get: (value => () => value)(makeFn()) //make a getter from an IIFE
}
})
console.log(obj3.foo()); // foo
console.log(obj3.bar()); // bar
console.log(obj3.baz()); // baz
Use a proxy (slight cheating)
This is an alternative. Define a Proxy that intercepts all calls to the object and this can directly tell you what was called. It's a bit of a cheat, as the function doesn't really lookup itself but from the outside it might look like this.
Still probably worth listing, as it has the advantage of being extremely powerful with a low overhead cost. No need to recursively walk the prototype chain and all possible properties to find the one:
"use strict";
//make a symbol to avoid looking up the function by its name in the proxy
//and to serve as the placement for the name
const tellMe = Symbol("Hey, Proxy, tell me my key!");
const fn = function ItrustTheProxyWillTellMe() {
return `My name is: ${ItrustTheProxyWillTellMe[tellMe]}`;
}
fn[tellMe] = true;
const proxyHandler = {
get: function(target, prop) { ///intercept any `get` calls
const val = Reflect.get(...arguments);
//if the target is a function that wants to know its key
if (val && typeof val === "function" && tellMe in val) {
//attach the key as ##tellMe on the function
val[tellMe] = prop;
}
return val;
}
};
//all properties share the same function
const protoObj = Object.defineProperties({}, {
foo: {
value: fn,
enumerable: true
},
bar: {
value: fn,
enumerable: false
},
baz: {
get() { return fn; }
}
});
const derivedObj = Object.create(protoObj);
const obj = new Proxy(derivedObj, proxyHandler);
console.log(obj.foo()); // foo
console.log(obj.bar()); // bar
console.log(obj.baz()); // baz
Take a peek at the call stack
This is sloppy and unreliable but still an option. It will be very dependant on the environment where this code, so I will avoid making an implementation, as it would need to be tied to the StackSnippet sandbox.
However, the crux of the entire thing is to examine the stack trace of where the function is called from. This will have different formatting in different places. The practice is extremely dodgy and brittle but it does reveal more context about a call than what you can normally get. It might be weirdly useful in specific circumstances.
The technique is shown in this article by David Walsh and here is the short of it - we can create an Error object which will automatically collect the stacktrace. Presumably so we can throw it and examine it later. Instead we can just examine it now and continue:
// The magic
console.log(new Error().stack);
/* SAMPLE:
Error
at Object.module.exports.request (/home/vagrant/src/kumascript/lib/kumascript/caching.js:366:17)
at attempt (/home/vagrant/src/kumascript/lib/kumascript/loaders.js:180:24)
at ks_utils.Class.get (/home/vagrant/src/kumascript/lib/kumascript/loaders.js:194:9)
at /home/vagrant/src/kumascript/lib/kumascript/macros.js:282:24
at /home/vagrant/src/kumascript/node_modules/async/lib/async.js:118:13
at Array.forEach (native)
at _each (/home/vagrant/src/kumascript/node_modules/async/lib/async.js:39:24)
at Object.async.each (/home/vagrant/src/kumascript/node_modules/async/lib/async.js:117:9)
at ks_utils.Class.reloadTemplates (/home/vagrant/src/kumascript/lib/kumascript/macros.js:281:19)
at ks_utils.Class.process (/home/vagrant/src/kumascript/lib/kumascript/macros.js:217:15)
*/
TL:DR; Is it possible to make a property of object to be invocable ( as a function ) only ?
What i mean by this
class Foo{
bar(value){
return value
}
}
let newFoo = new Foo()
console.log(newFoo.bar(123)) // should work fine as function is invoked
console.log(newFoo.bar) // here i need to throw or display an error instead of returning value
I tried to do this with Proxy and handler.get trap, but i have no clue how to capture whether it is a function call or just property access,
class Foo {
bar(value) {
return value
}
}
const proxied = new Proxy(new Foo(), {
get: function(target, prop, reciver) {
if (prop === 'bar') {
throw new Error('Bar is method need to be invoced')
}
return target[prop]
}
})
console.log(proxied.bar(true))
console.log(proxied.bar)
I have also checked handler.apply but this also doesn't seems to be of no use as this is a trap on function, not on property
class Foo {
bar(value) {
return value
}
}
const proxied = new Proxy(new Foo(), {
apply: function(target, thisArg, argumentsList) {
return target(argumentsList[0])
},
get: function(target, prop, reciver) {
if (prop === 'bar') {
throw new Error('Bar is method need to be invoced')
}
return target[prop]
}
})
console.log(proxied.bar(true))
console.log(proxied.bar)
No, this is not possible. There is no distinction between
const newFoo = new Foo()
newFoo.bar(123);
and
const newFoo = new Foo()
const bar = newFoo.bar;
Function.prototype.call.call(bar, newFoo, 123); // like `bar.call(newFoo, 123)`
// or Reflect.apply(bar, newFoo, [123]);
i.e. neither newFoo nor bar can distinguish these "from the inside". Now arbitrary things could happen in between the property access and the method call, and during the property access you cannot know what will happen next, so you cannot throw an exception prematurely. The method call might happen never (in newFoo.bar;), and there's no way to recognise that from newFoo alone.
The only approach would be to intercept all other accesses on newFoo and its properties, and throw after you detected a mischievous sequence; possibly having your "linter" check the sequence from the outside after the whole program ran:
const lint = {
access: 0,
call: 0,
check() {
console.log(this.access == this.call
? "It's ok"
: this.access > this.call
? "method was not called"
: "property was reused");
},
run(fn) {
this.call = this.access = 0;
try {
fn();
} finally {
this.check();
}
}
}
function bar(value) {
lint.call++; lint.check();
return value;
}
class Foo {
get bar() {
lint.check(); lint.access++;
return bar;
}
}
lint.run(() => {
const newFoo = new Foo;
newFoo.bar(123);
});
lint.run(() => {
const newFoo = new Foo;
newFoo.bar;
});
lint.run(() => {
const newFoo = new Foo;
const bar = newFoo.bar;
bar(123);
bar(456);
});
The better solution would probably to write your own interpreter for simple expressions, which would only allow method calls.
I want to get the name of the current method from within an instance method of a class in Typescript.
(Pseudocode, doesn't work):
class Foo {
bar() {
console.log(something); //what should something be?
}
}
new Foo().bar();
I expect 'something' to return 'bar'. I realize that this can give me the class, and I could somehow get the class and its attributes from it, but I do not know how to get 'this function' (i.e, the method bar, not the class Foo).
I have seen several other questions related to finding the class name, etc. but not one that addresses getting the current method name.
Besides the arguments.callee.name there is no straightforward way of getting this.
I propose 2 other methods:
Use decorators to inject the method name:
function annotateName(target, name, desc) {
var method = desc.value;
desc.value = function () {
var prevMethod = this.currentMethod;
this.currentMethod = name;
method.apply(this, arguments);
this.currentMethod = prevMethod;
}
}
class Foo {
currentMethod: string;
#annotateName
bar() {
alert(this.currentMethod);
this.tux();
alert(this.currentMethod);
}
#annotateName
tux() {
alert(this.currentMethod);
}
}
new Foo().bar();
The downside is that you have to annotate all the functions you want to get the name from. You could instead just annotate the class and in the decorator you would iterate over all prototype functions and apply the same idea.
My second option is not standardised and need more care to get consistent results across browsers. It relies on creating an Error object and getting it's stack trace.
class Foo {
bar() {
console.log(getMethodName());
}
}
function getMethodName() {
var err = new Error();
return /at \w+\.(\w+)/.exec(err.stack.split('\n')[2])[1] // we want the 2nd method in the call stack
}
new Foo().bar();
Not sure if this would help, but:
class Foo {
bar() {
console.log(Object.getOwnPropertyNames(Foo.prototype)); // ["constructor", "bar"]
}
}
new Foo().bar();
Here is my solution to get the method name.
/**
* #description Get log invoker name
* #return {string} The invoker name
*/
private static callerName(): string {
try {
throw new Error();
} catch (e) {
try {
return e.stack.split('at ')[3].split(' ')[0];
} catch (e) {
return '';
}
}
}
I was looking for a solution as well, try this:
class Foo {
bar() {
console.log(this.bar.name); // <-- Print out the function name.
}
}
new Foo().bar();
What is nice is that you'll get an error if you change the function name, but forget to update the console statement.
Keep in mind that during compilation and minification you might lose the actual name of what you're trying to use. You might consider looking into the ts-nameof babel macro that reads the name of virtually anything during compilation and returns it's actual string representation.
for class name - Foo.name
for method name - this.bar.name
Just to answer the question with another interesting take, you could do (but shouldn't do) something like this:
class Foo {
constructor(private http: HttpClient) {
const apiUrl = 'http://myapi.com/api/';
{
const functionName = 'getBar';
this[functionName] = function () {
return http.get(apiUrl + functionName);
}
}
{
const functionName = 'postBar';
this[functionName] = function () {
return http.get(apiUrl + functionName);
}
}
{
const functionName= 'putBar';
this[functionName] = function () {
return http.get(apiUrl + functionName);
}
}
{
const functionName= 'deleteBar';
this[functionName] = function () {
return http.get(apiUrl + functionName);
}
}
}
}
It certainly is not an elegant solution, and I can't really imagine a good use case for doing something like this, as I'm pretty sure the compiler doesn't recognize new Foo(http).deleteBar(). Maybe someone can come up with an elegant solution with this idea, I'll leave that as an experiment for someone.
But with this pattern (if you employ some kind of devops scaffolding or "strong copy-paste skills") you can always access your method's name via functionName
function getFunctionName() {
return getFunctionName.caller.name
}
function foobar() {
console.log(getFunctionName())
}
foobar() // logs 'foobar' as the currently running function
You can use the .caller property:
A Function object's caller property accessor property represents the function that invoked the specified function. For strict, async function, and generator function callers, accessing the caller property throws an exception.
Although non standard, in my experience the caller property is supported everywhere I have used it (mostly node.js). Check for compatibility before using it. I have only every used it for debugging purposes. For more information, please see
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller
I'm a little bit confused with the class feature in es2016, though it is assumed to be just a syntax sugar for creating classes, in comparison to function and prototype, but the behaviour in some cases is different, in particular - classes can't be called same as functions and it seems, there is no way to find out if a function is the class constructor or a simple function, without using toString and the /^class/ RegExp.
Assume the example:
class Foo {
constructor () {
this.name = 'foo';
}
}
function Bar () {
this.name = 'bar';
}
function doSmth (anyArg) {
if (typeof anyArg === 'function') {
var obj = { someProp: 'qux' };
anyArg.call(obj);
return obj;
}
// ...
}
doSmth(Bar);
doSmth(Foo); // Class constructor Foo cannot be invoked without 'new'
Is typeof 'function', but can't call it as a function! Nice.
And here are my 2 questions:
Is there some way I can call the Foo constructor function same as Bar with the overriden this context?
Is there some way I can detect the anyArg is the constructor of a class, sothat I can handle it differently in my doSmth function. Without toString and the RegExp (as the performance penalty would be huge in this case). I could then use Reflect.construct to initialize the new instance, and Object.assign to extend my obj variable with the values from the instance.
Thank you, Alex
No to both questions.
Here's how Angular 1.x detects classes:
function isClass(func) {
// IE 9-11 do not support classes and IE9 leaks with the code below.
if (msie <= 11 || typeof func !== 'function') {
return false;
}
var result = func.$$ngIsClass;
if (!isBoolean(result)) {
// Support: Edge 12-13 only
// See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/
result = func.$$ngIsClass = /^(?:class\b|constructor\()/.test(stringifyFn(func));
}
return result;
}
Unfortunately, it's the best possible solution. And it even doesn't work in Firefox at that.
I'm not aware of a way to do what you ask in your first question.
For the second question, you actually identified a method to tell the difference yourself. One of the differences between a class constructor and a function used as a constructor is that the former errors when using it without the new keyword, and the latter doesn't.
So, if we use a try/catch, we can do roughly what you want:
class Foo {
constructor () {
this.name = 'foo';
}
}
function Bar () {
this.name = 'bar';
}
function doSmth (anyArg) {
if (typeof anyArg === 'function') {
var obj = { someProp: 'qux' };
try {
anyArg.call(obj);
} catch(e) {
var x = Reflect.construct(anyArg, []);
Object.assign(obj, x);
}
return obj;
}
}
doSmth(Bar);
doSmth(Foo);
To be clear, I'm not suggesting this is a good idea, good code, or that it has the performance you're looking for, but I thought I'd point out that the possibility does exist.
If you're concerned about the performance penalty of RegEx then use substring(). If you're still concerned about the performance of string operations, then consider another language that actually differentiates function types. In JavaScript they're all function.
class Foo {
constructor() {
this.name = 'foo';
}
}
function Bar() {
this.name = 'bar';
}
function doSmth(anyArg) {
if (typeof anyArg === 'function') {
var obj = {
someProp: 'qux'
};
if (anyArg.toString().substring(0, 5) === 'class') {
Object.assign(obj, new anyArg());
} else {
anyArg.call(obj);
}
return obj;
}
// ...
}
var bar = doSmth(Bar);
var foo = doSmth(Foo);
console.log(bar);
console.log(foo);
I am new to javascript. I have a function taking an object. But how do I make sure caller is following the structure I want in the object. As there is no concept of class in javascript, I can't create a model class and make the caller use it ?
function foo(myObject)
{
}
Whoever is calling should give me
{
Count,
[
{
FirstName,
LastName
},
{
FirstName,
LastName
},
]
}
Well you could simply check the type of object you have received as an argument, and then check if those values are actually there, like so:
function foo(myObject) {
if (typeof myObject !== 'object') {
// doesn't match
return;
}
if (typeof myObject.Count === 'undefined') {
// no count property
}
}
However, from your question, it seems you would like to make it more fix which kind of object should be sent as an argument, and this you could also do in javascript, by doing for eg:
function MyParamOptions() {
// define properties here
this.persons = [];
Object.defineProperty(this, 'Count', {
get: function() {
return this.Names.length;
},
set: function() {
// dummy readonly
}
});
}
Then you could instantiate an instance of this class by saying
var options = new MyParamOptions();
options.persons.push({ firstName: 'bla', lastName: 'bla' });
and change a check inside your foo function like
function foo(myObject) {
if (myObject instanceof MyParamOptions) {
// here myObject is MyParamOptions, so you can access the persons array, the Count property etc...
}
}
// and call foo with your MyParamOptions
foo(options);
However this will not throw any warnings at compile time, so people can call your function with any kind of parameter. If you are looking for errors at compile time, you might look into TypeScript or a similar technology that then transpiles your TypeScript code to javascript)