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.)

3
  • Maybe similar question: stackoverflow.com/questions/3710275/… Commented Sep 14, 2013 at 21:30
  • @jsmorph No, this is about TypeScript. Commented Sep 14, 2013 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). Commented Sep 18, 2013 at 3:09

1 Answer 1

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";
Sign up to request clarification or add additional context in comments.

3 Comments

This will not compile - it gives me a Duplicate identifier 'Foo'. for function Foo(bar) {...}!
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
Thanks, I was trying to integrate a pure Javascript library with typescript and this did the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.