[英]Typescript interface A extends B, but is missing properties from B?
I don't understand how TypeScript interfaces work, apparently.显然,我不明白 TypeScript 接口是如何工作的。 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.我在这里尝试做的是通过添加“id”属性并扩展“handshake”属性来扩展 socket.io 给定的“Socket”接口。 The latter is not accepted by TypeScript. TypeScript 不接受后者。 TS claims that "SessionHandshake is missing x, y, z properties from type Handshake". TS 声称“SessionHandshake 缺少 Handshake 类型的 x、y、z 属性”。 But how can this be?但这怎么可能呢? I defined SessionHandshake as an extension of the Handshake interface.我将 SessionHandshake 定义为 Handshake 接口的扩展。 How can TS claim it does not have all of Handshake's properties? TS 怎么能声称它不具备 Handshake 的所有属性?
Using TS 4.1.3 here.在这里使用 TS 4.1.3。
The keyword extends
can be used for interfaces and classes only.关键字extends
只能用于接口和类。
Handshake
is a type, therefore you cannot use the keyword extends
Handshake
是一种类型,因此您不能使用关键字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 };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.