首页 > 解决方案 > 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!!

我想知道为什么第二行是错误的?我不想使用第一行,这很麻烦。但第二行是行不通的。我说。

标签: typescript

解决方案


github上也有关于这个问题的建议:https ://github.com/microsoft/TypeScript/issues/31843

一般而言 - Element['position'](在扩展classor时interface)被评估为表达式,而不是类型。

您可以通过以下方式解决它:

  1. 正如您通过首先声明类型所做的那样type Pos = Element['position']
  2. 使其更通用,以便在您的项目中重用它:

    type Take<T> = T
    interface Bar extends Take<Element['position']> {
    
    }
    
  3. 哈奇解决方法:

    interface Bar extends Omit<Element['position'], ''> {
    
    }
    

推荐阅读