I have a generic interface like this example with a single type constraint:
export interface IExample<T extends MyClass> { getById(id: number): T; }
Is it possible to specify multiple type constraints instead of just one?
There can be more than one constraint associated with a type parameter. When this is the case, use a comma-separated list of constraints. In this list, the first constraint must be class or struct or the base class.
Using type parameters in generic constraintsTypeScript allows you to declare a type parameter constrained by another type parameter. The following prop() function accepts an object and a property name. It returns the value of the property.
TypeScript Generics is a tool which provides a way to create reusable components. It creates a component that can work with a variety of data types rather than a single data type. It allows users to consume these components and use their own types.
Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.
Typescript doesn't offer a syntax to get multiple inheritance for generic types. However, you can achieve similar semantics by using the Union types and Intersection types. In your case, you want an intersection :
interface Example<T extends MyClass & OtherClass> {}
For a Union of both types :
interface Example<T extends MyClass | OtherClass> {}
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