Home > Software engineering >  intersection interface is valid in typescript?
intersection interface is valid in typescript?

Time:11-26

I know the difference between type and interface, but what I'm confusing is that I can make type from interface.

For example

import React, { useState } from "react";
import "./styles.css";

interface Props1 {
  age: number;
}

interface Props2 {
  name: string;
}

type Props = Props1 & Props2; // ====>>>> why is this possible ??

const App: React.FC<Props> = () => {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
};

export default App;

I can not find any docs of it from the typescript handbook. I want to know why this is possible.

CodePudding user response:

Intersection actually is not the same as extension. Even though these tools usually serve the same purpose.

I think this piece of TS documentation should be useful for you. Short quote from it:

interfaces allowed us to build up new types from other types by extending them. TypeScript provides another construct called intersection types that is mainly used to combine existing object types.

CodePudding user response:

Props1 and Props2 are interfaces. an interface is a named ObjectType.

Props1 and Props2 as ObjectType are also PrimaryType. Indeed, a PrimaryType is defined as follows

PrimaryType:
ParenthesizedType
PredefinedType
TypeReference
ObjectType
ArrayType
TupleType
TypeQuery
ThisType

PrimaryType can be used as building blocks of IntersectionType. Indeed, the IntersectionType syntax is the following:

IntersectionType:
IntersectionOrPrimaryType & PrimaryType

So, Props1 & Props2 is valid, since Props1 and Props2 are PrimaryType and results into an IntersectionType.

Props is a type alias, and the declaration syntax of type alias is the following:

TypeAliasDeclaration:
type BindingIdentifier TypeParametersopt = Type ;

As you can see, you only authorized to assign a Type to a type alias. in your example this means that Props1 & Props2 needs to be a Type to be assignable.

What is a Type ?

A Type is defined as:

Type:
UnionOrIntersectionOrPrimaryType
FunctionType
ConstructorType

Since Props1 & Props2 is an IntersectionType, this means it is also a Type, and so assignable to Props

  • Related