Jonathan.Brink
Jonathan.Brink

Reputation: 25403

Defining an intersection using interface, not type

Given an intersection type like this:

type Combination = Type1 & Type2;

How can it be written using an interface?

This attempt doesn't compile:

interface Combination = Type1 & Type2;

Upvotes: 1

Views: 167

Answers (2)

Silvio Mayolo
Silvio Mayolo

Reputation: 70287

You can't, in general. In theory, we could get it by extending the type

interface Combination extends (Type1 & Type2) {}

But the language's grammar won't allow that. Only qualified identifiers (potentially with type arguments) can be used in an "extends" clause.

Note that we can use type aliases in an "extends" clause, so the following technically answers your question

type TemporaryName = Type1 & Type2
interface Combination extends TemporaryName {}

Combination is an interface that represents an intersection type. But that's a very mathematical and unhelpful answer, if your goal is to avoid using type aliases.

Upvotes: 2

Mic Fung
Mic Fung

Reputation: 5692

Type union to interface can be translated into

interface Type1 { name: string }
interface Type2 { id: number }
interface Combination extends Type1, Type2 {}

Upvotes: 2

Related Questions