Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a typescript property that implements multiple interfaces

Tags:

typescript

Say I have 2 interfaces:

interface Interface1{}
interface Interface2{}

is there a way to declare a property as implementing both interfaces? Something like:

class MyClass{
  public p: Interface1, Interface2
}
like image 779
J2K Avatar asked Jun 07 '16 01:06

J2K


People also ask

Can you implement multiple interfaces in TypeScript?

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.

What does ?: Mean in TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

Can TypeScript interface have implementation?

Similar to languages like Java and C#, interfaces in TypeScript can be implemented with a Class.

How do you pass an interface as a parameter TypeScript?

An interface type cannot be passed as a parameter. When running TypeScript code, you are really compiling it down to JavaScript and then running the JavaScript. An interface is a TypeScript compile-time construct, so at runtime, there is no such thing as an interface type to call functions on or inspect properties of.


1 Answers

is there a way to declare a property as implementing both interfaces? Something like:

Yup. An intersection type:

interface Interface1{}
interface Interface2{}
class MyClass{
  public p: Interface1 & Interface2
}

More

  • TypeScript Intersection Types: https://basarat.gitbook.io/typescript/type-system#intersection-type
like image 68
basarat Avatar answered Sep 30 '22 17:09

basarat