there are function in 3rd party libraries that extends objects to add to them more functions. e.g. seamless-immutable
I want to create definition file for such a library. I thought something in the line of
interface ImmutableMethods<T> extends T{
set?<U>(key: string | number, value: any): T | U;
setIn?<U>(keys: Array<string>, value: any): T | U;
...
}
function Immutable<T>(obj: T, options?): ImmutableMethods<T>
Then I will be able to declare my own types as:
interface Type1 {prop1, prop2}
interface Type2 {propOfType1: ImmutableMethods<Type1>}
var immutableType2:Type2 = Immutable(...)
And then I'll have the Immutable's function on all my objects.
But the problem is that the line interface ImmutableMethods<T> extends T
gives me an error "An interface may only extend a class or another interface"
Is there a way to declare that T is an interface, or a whole other way to get this extending behavior?
You can use intersection types to attain this behavior. Define an interface for the extra functions and define a type that is T & Interface. My modifications to your code:
interface ImmutableMethods<T> {
set?<U>(key: string | number, value: any): T | U;
setIn?<U>(keys: Array<string>, value: any): T | U;
}
type ImmutableExtended<T> = ImmutableMethods<T> & T;
interface Type1 { prop1: string, prop2: string }
interface Type2 { propOfType1: ImmutableExtended<Type1> }
var immutableType2: Type2 = ...;
The ImmutableMethods<T>
interface defines the functions involved. The ImmutableExtended<T>
type is the interface we actually want to use for the extended objects, though of course you can name these interfaces whatever you like.
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