Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The new Operator

Is it possible to write a javascript function that follows this (valid) typescript interface:

interface Foo{
    // constructor: 
    new (): string; 
}

i.e. Something that when called with a new operator returns a string. e.g. the following will not work.

function foo(){
    return "something";
} 
var x = new foo(); 
// x is now foo (and not string) whether you like it or not :) 
like image 478
basarat Avatar asked Dec 06 '25 19:12

basarat


1 Answers

You should be able to do:

function foo(){
    return new String("something");
} 
var x = new foo(); 

console.log(x);

You can return any object, but literals don't work. See here: What values can a constructor return to avoid returning this?

like image 166
RobH Avatar answered Dec 08 '25 08:12

RobH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!