Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare Typescript Interface for non Typescript class

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

like image 281
laktak Avatar asked May 28 '26 05:05

laktak


1 Answers

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";
like image 149
basarat Avatar answered Jun 03 '26 08:06

basarat



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!