How to create typescript definitions for a function that extends objects

There are functions in third-party libraries that extend objects to add more functions to them. e.g. seamless-immutable

I want to create a definition file for such a library. I thought something in the line

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 can declare my own types as:

 interface Type1 {prop1, prop2} interface Type2 {propOfType1: ImmutableMethods<Type1>} var immutableType2:Type2 = Immutable(...) 

And then I will have an Immutable function for all my objects.

But the problem is that the line interface ImmutableMethods<T> extends T gives me the error "An interface can only extend a class or another interface"

Is there a way to declare that T is an interface or a completely different way to get this extended behavior?

+5
source share
1 answer

You can use intersection types to achieve this behavior. Define an interface for additional functions and define a type that is T and an interface. My changes 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 related functions. The ImmutableExtended<T> is the interface we really want to use for extended objects, although, of course, you can name these interfaces as you like.

+1
source

Source: https://habr.com/ru/post/1243637/


All Articles