typescript - TypeScript:接口如何扩展从具有属性的其他接口检索到的类型
问题描述
interface Element {
name: string
position: {
x: number
y: number
}
}
type Pos = Element['position']
interface Pos1 extends Position { } // works here
interface Pos2 extends Element['position'] { } // not work!!
我想知道为什么第二行是错误的?我不想使用第一行,这很麻烦。但第二行是行不通的。我说。
解决方案
github上也有关于这个问题的建议:https ://github.com/microsoft/TypeScript/issues/31843
一般而言 - Element['position']
(在扩展class
or时interface
)被评估为表达式,而不是类型。
您可以通过以下方式解决它:
- 正如您通过首先声明类型所做的那样
type Pos = Element['position']
。 使其更通用,以便在您的项目中重用它:
type Take<T> = T interface Bar extends Take<Element['position']> { }
哈奇解决方法:
interface Bar extends Omit<Element['position'], ''> { }
推荐阅读
- c# - 在 C# 中创建时如何使 System.Windows.Forms.Panel 填充 WPF 中的容器?
- reactjs - 如何在 redux 工具包中模拟 store
- design-patterns - 什么是软件工程中的“通用层次模式”?
- python - Python - 如何打开多个浏览器窗口并在这些窗口上运行选项卡?
- javascript - 我如何从子函数中获取价值
- powershell - 如何使用 Powershell 将十六进制字符串转换为 bin?
- javascript - 如何在 QML 中使用 TableView 从 QtQuickControls 1 获取列数据?
- react-native - 选择值时反应材质UI关闭 - 多选
- php - 如何将 2 个 json 数据与具有不同键但相同值的 php 结合起来
- mysql - 为每个人选择最早的记录