Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid missing property TypeScript error on types extending a function or array

Tags:

typescript

When I define an interface which extends from a function or array, I have not found a way to properly create new instances without getting an error or using an any cast.

Is there a way to initialize such members without reverting to hacks?

Example with Function:

interface Foo {
    bar: any;
    (): void;
}

// how to create a Foo?
var foo: Foo;
foo = () => {}; // cannot convert type ... has non-optional property bar which is not present
foo.bar = "initialized!";

Example with Array:

interface Foo<T> extends Array<T> {
    bar: any;
}

// how to create a Foo?
var foo: Foo<any>;
foo = []; // cannot convert type ... has non-optional property bar which is not present
foo.bar = "initialized!";
like image 703
Lucero Avatar asked Feb 06 '16 22:02

Lucero


1 Answers

Perhaps you are looking for the optional operator

interface Foo<T> extends Array<T> {
  bar?: any;
}

var foo: Foo<any>;
foo = []; // No error

Placing the ? after a property name but before the : makes the property optional. This means that the property does not have to exist but could.

UPDATE

If you do want the property to be required by the contract, then you will need to cast it. This is because TypeScript requires all objects that are instantiated with a literal ([], or {}) to include all required members. The correct way to instantiate this without including a required property is to use a cast. Either foo = <any>[]; or foo = <Foo><any>[];

like image 180
SnareChops Avatar answered Oct 11 '22 18:10

SnareChops