错误消息:“接口只能扩展对象类型或对象类型与静态已知成员的交集" [英] Error Message: "An interface can only extend an object type or intersection of object types with statically known members"

查看:132
本文介绍了错误消息:“接口只能扩展对象类型或对象类型与静态已知成员的交集"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

export type Partial2DPoint = { x: number } | { y: number }
export interface Partial3DPoint extends Partial2DPoint {
  z: number
}

失败并出现以下错误:

接口只能扩展对象类型或对象类型与静态已知成员的交集.

An interface can only extend an object type or intersection of object types with statically known members.

为什么会这样?

推荐答案

类型与接口在扩展联合类型的能力上有所不同

(我在回答我自己的问题)这是因为您不能使用接口扩展联合类型.您必须使用类型别名:

Types vs Interfaces differ in the ability to extend union types

(I'm answering my own question) This is because you cannot extend a union type using an interface. You must use type alias:

export type Partial2DPoint = { x: number } | { y: number }
export type Partial3DPoint = Partial2DPoint & { z: number }

看到这个答案:

类可以以完全相同的方式实现接口或类型别名.但是请注意,类和接口被视为静态蓝图.因此,他们无法实现/扩展命名联合类型的类型别名.

A class can implement an interface or type alias, both in the same exact way. Note however that a class and interface are considered static blueprints. Therefore, they can not implement / extend a type alias that names a union type.

这篇关于错误消息:“接口只能扩展对象类型或对象类型与静态已知成员的交集"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆