I want to make a placeholder interface for classes that use an external library. So I made:
export interface IDatabaseModel extends any
{
}
I'd rather do this and add methods later (e.g. findAll()) than mark all my classes as 'any' and have to manually search and replace 'any' in hundreds of specific places with 'IDatabaseModel' later.
But the compiler complains it cannot find 'any'.
What am I doing wrong?
We can extend interfaces with the extends keyword. We can use the keyword to extend one or more interfaces separated by commas. For example, we can use the extends keyword as in the code below: Then, to implement the Dog and Cat interfaces, we have to implement the members listed in the Animal interface as well.
Use an intersection type to extend a type in TypeScript, e.g. type TypeB = TypeA & {age: number;} . Intersection types are defined using an ampersand & and are used to combine existing object types. You can use the & operator as many times as necessary to construct a type.
An interface can be extended by other interfaces. In other words, an interface can inherit from other interface. Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.
An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.
any
I want to make a placeholder interface
Use an alias:
type IDatabaseModel = any;
Since TypeScript 2.2, the property access syntax obj.propName
is allowed with an index signature:
interface AnyProperties {
[prop: string]: any
}
type MyType = AnyProperties & {
findAll(): string[]
}
let a: MyType
a.findAll() // OK, with autocomplete
a.abc = 12 // OK, but no autocomplete
2020 TLDR:
instead of extends any
try extends Record<string, any>
.
Long version:
In certain cases extends any
still works in TypeScript. However, in TypeScript 3.9, it is interpreted in a more conservative way.
@Paleo creates AnyProperties
interface in his answer. That can now be rewritten with Record as extends Record<string, any>
.
The any
type is a way to opt-out of type checking and so it doesn't make sense to use it in an environment where type checking is done.
You could instead add your methods to the interface as you use them:
export interface IDatabaseModel
{
findAll(): any;
}
Edit: See Paleo's answer for using a type alias in the meantime.
"any" is a type and, unlike other basic types, doesn't appear to have an interface. Given it is a wildcard of sorts, I can't imagine what an interface to "any" could consist of.
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