简体   繁体   English

打字稿定义文件和扩展外部类型

[英]Typescript definition files and extending external types

I'm trying to extend one of my own types from an external type. 我正在尝试从外部类型扩展我自己的类型之一。

Since I don't really know what I'm doing I am putting these in the global.d.ts file. 由于我真的不知道我在做什么,所以将它们放在global.d.ts文件中。

Previous to doing this I have been importing types into every typescript file in my project which seems wrong and messy (30 import lines on the top of every file). 在执行此操作之前,我一直将类型导入到项目中的每个打字稿文件中,这似乎是错误且混乱的(每个文件顶部有30条导入行)。

global.d.ts file works when I just have my code in it 当我只有代码时,global.d.ts文件就可以工作

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

Where my understanding stops is what if I have a type that needs to extend one that's external. 如果我有一个需要扩展外部类型的类型,那我的理解就会停止。

(For example I'm going to try to extend the Redux action type). (例如,我将尝试扩展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
}

I can successfully get typescript to stop complaining that it can't find 'name Action' if I change the file to this 我可以成功获取打字稿,以停止抱怨如果将文件更改为“ name Action”,则找不到此文件

import * as Redux from 'redux';

interface IPerson {
  name: string
}

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

Except now every file that uses IPerson can no longer find it. 除了现在,所有使用IPerson的文件都无法找到它。 I don't understand why. 我不明白为什么。 Anytime I add an import to a declaration file it breaks everything else, but fixes the declaration file. 每当我将导入添加到声明文件时,它都会破坏其他所有内容,但会修复声明文件。

What am I doing wrong here? 我在这里做错了什么? I'm looking for a place I can put all my types, if there's a better way to get typescript to recognize my types I'm open to other options. 我正在寻找可以放置所有类型的地方,如果有更好的方法来使打字稿识别我的类型,我可以接受其他选择。

I think you need to export the interface from your module: 我认为您需要从模块中export接口:

import * as Redux from 'redux';

export interface IPerson {
  name: string
}

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

and then import the same at the place of usage: 然后在使用位置import相同的内容:

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

PS Though it is not a problem, you might want to loose the 'I' from the name of interfaces . PS虽然这不是问题,但您可能想从接口名称中删除“ I”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM