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!";
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>[];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With