trollkotze
trollkotze

Reputation: 1139

Typescript interface A extends B, but is missing properties from B?

I don't understand how TypeScript interfaces work, apparently. I have this:

import type { Socket, Handshake } from 'socket.io';
import type { Session } from './session';

export interface SessionHandshake extends Handshake {
  session: Session;
}

export interface SessionSocket extends Socket {
  handshake: SessionHandshake;
  id: string;
}

What I'm trying to do here is extending the given "Socket" interface from socket.io, by adding an "id" property and extending the "handshake" property. The latter is not accepted by TypeScript. TS claims that "SessionHandshake is missing x, y, z properties from type Handshake". But how can this be? I defined SessionHandshake as an extension of the Handshake interface. How can TS claim it does not have all of Handshake's properties?

Using TS 4.1.3 here.

Upvotes: 3

Views: 2547

Answers (1)

Yash T
Yash T

Reputation: 141

The keyword extends can be used for interfaces and classes only.

Handshake is a type, therefore you cannot use the keyword extends

If you just want to declare a type that has additional properties, you can use an intersection type:

export type SessionHandshake = Handshake & { session: string };

Upvotes: 1

Related Questions