【问题标题】:Typescript definition files and extending external types打字稿定义文件和扩展外部类型
【发布时间】:2017-04-01 17:20:56
【问题描述】:

我正在尝试从外部类型扩展我自己的一种类型。

因为我真的不知道自己在做什么,所以我将这些放在 global.d.ts 文件中。

在执行此操作之前,我一直在将类型导入项目中的每个打字稿文件,这似乎是错误且混乱的(每个文件顶部有 30 条导入行)。

global.d.ts 文件只在我的代码中有效

// successfully can use this anywhere
interface IPerson {
   name: string
}

如果我有一个需要扩展外部类型的类型,我的理解就停止了。

(例如我将尝试扩展 Redux 操作类型)。

/// <reference path="../node_modules/redux/index.d.ts" />

interface IPerson {
  name: string
}

// even with the reference typescript 'cannot find name Action'
interface PersonAction extends Action {
   person?: IPerson
}

如果我将文件更改为此,我可以成功地让 typescript 停止抱怨它找不到“name Action”

import * as Redux from 'redux';

interface IPerson {
  name: string
}

interface PersonAction extends Redux.Action {
  person?: IPerson
}

除了现在每个使用 IPerson 的文件都找不到它。我不明白为什么。每当我向声明文件添加导入时,它都会破坏其他所有内容,但会修复声明文件。

我在这里做错了什么?我正在寻找一个可以放置所有类型的地方,如果有更好的方法让 typescript 识别我的类型,我愿意接受其他选择。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我认为您需要 export 模块中的接口:

    import * as Redux from 'redux';
    
    export interface IPerson {
      name: string
    }
    
    export interface PersonAction extends Redux.Action {
      person?: IPerson
    }
    

    然后import在使用的地方也一样:

    import {IPerson, PersonAction} from 'your-module'
    

    附:虽然这不是问题,但您可能想loose the 'I' from the name of interfaces

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      • 2017-04-19
      • 2017-06-18
      • 2020-08-18
      相关资源
      最近更新 更多