Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can You Specify Multiple Type Constraints For TypeScript Generics

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?

like image 281
Fenton Avatar asked Jun 15 '13 16:06

Fenton


People also ask

Can a generic class have multiple constraints?

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.

What's the idea behind TypeScript constraints when talking about generics )?

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.

What are some properties of generics in TypeScript?

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.

How do you define a generic type in TypeScript?

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.


1 Answers

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> {} 
like image 126
STO Avatar answered Sep 20 '22 08:09

STO