3

Is it possible to declare a TypeScript interface for a plain JavaScript class?

e.g.

function Foo(bar)
{
  this.bar=bar;
}

var x=new Foo("test"); // x is shown as any

I'd like to declare an interface for Foo:

interface IFoo
{
  bar: string;
}

But I can't figure out how to declare it.

function Foo(bar: string) : IFoo
{
  this.bar=bar;
}

Gives me "'Foo' declared a non-void return type, but has no return expression."

(I don't want to rewrite Foo as a TypeScript class.)

laktak
  • 57,064
  • 17
  • 134
  • 164
  • Maybe similar question: http://stackoverflow.com/questions/3710275/does-javascript-have-the-interface-type-such-as-javas-interface – jsmorph Sep 14 '13 at 21:30
  • @jsmorph No, this is about TypeScript. – laktak Sep 14 '13 at 21:56
  • As @basarat says, separate your JavaScript code from TypeScript code, or convert your JavaScript code into TypeScript (which will compile into a version similar to your original JavaScript code). – Stephen Chung Sep 18 '13 at 03:09

1 Answers1

4

You can simply declare it to be a class :

declare class Foo{
    bar:string;
    constructor(bar:string);
}

var x=new Foo("test"); // x of type foo
x.bar="lala";
basarat
  • 261,912
  • 58
  • 460
  • 511
  • This will not compile - it gives me a `Duplicate identifier 'Foo'.` for `function Foo(bar) {...}`! – laktak Sep 15 '13 at 13:05
  • 4
    You need to put the JavaScript code in JavaScript. You cannot type in typescript and tell the compiler that this is a class not a function – basarat Sep 15 '13 at 23:03
  • Thanks, I was trying to integrate a pure Javascript library with typescript and this did the trick. – cjohansson May 02 '17 at 12:55