简体   繁体   English

Typescript 接口 A 扩展了 B,但缺少 B 的属性?

[英]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.

相关问题 接口的属性仅在TypeScript中的类型为A和B? - Interface whose properties are of types A and B only in TypeScript? 打字稿:获取由接口 A 中存在但不在接口 B 中的属性组成的接口 - Typescript: Get interface that consist of properties that are present in interface A, but not in interface B TypeScript:“A 扩展 B”的键入问题 - TypeScript: Typing problem with “A extends B” Typescript 错误? Function 接受 Object 定义为接受类型 A 和 B 的联合,其中 B 扩展 A - Typescript bug? Function accepts Object with missing prop when defined to accept union of type A and B where B extends A 类型 A 缺少类型 B 的以下属性:a、b - Type A is missing the following properties from type B: a, b 当 Type B 以某种方式“扩展”Type A 时,如何停止 TypeScript 错误“Type A 没有与 Type B 相同的属性” - How to stop TypeScript error 'Type A has no properties in common with Type B' when Type B "extends" Type A in some way 为什么TypeScript声明对象文字`{a}`使用接口`{a,b}`而不是`{a?,b}` - Why does TypeScript assertion of object literal `{a}` work with interface `{a, b}` but not `{a?, b}` TypeScript - 如何将对象 A 的属性复制到扩展 A 的新对象 B 上 - 在旧 ts 版本上工作现已损坏 - TypeScript - how to copy object A's properties onto new object B that extends A - worked on older ts version now broken 接口中的打字稿变量var是否可以声明为A或B类型 - Can a typescript var in an interface be declared of type A or B 打字稿和(a,b)=> a + b - Typescript and (a, b) => a+b
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM