打字稿:将本地接口与外部接口合并的任何方法?

时间:2017-08-27 14:31:30

标签: typescript

所以我使用了here提供的简单对等的Typescript定义。但是,定义稍微过时,导致一些Typescript错误显示,如果定义被修改,它将有效。我已经提交了一个拉取请求来修复这些定义,但与此同时,我想知道是否有一种简单的方法来纠正我文件顶部的定义?

我当然可以将整个定义粘贴到一个新的本地文件中并进行更正,但希望有一个更优雅的解决方案。类似的东西:

import * as SimplePeer from "simple-peer";

interface SimplePeer.Options extends SimplePeer.Options{
    objectMode:boolean;
}

如果这是有效的Typescript,它只会将该额外属性合并到SimplePeer.Options的现有定义上。有没有一种有效的方法呢?

1 个答案:

答案 0 :(得分:1)

您应该只需指定SimplePeer.Options的新附加属性,而无需引用原始属性。 Typescript做declaration merging,其中一个例子是两个接口:

interface Box {
    height: number;
    width: number;
}

interface Box {
    scale: number;
}

let box: Box = {height: 5, width: 6, scale: 10};

我大量使用Immutable来允许对其集合进行迭代,因此它对外部库很有效(据我所知):

/* monkey-patch immutable to support es6 iteration */
declare module 'immutable' {
  // tslint:disable-next-line:no-shadowed-variable
  namespace Iterable {
    interface Indexed<T> {
      [Symbol.iterator](): IterableIterator<T>;
    }

    interface Iterator<T> {
      [Symbol.iterator](): IterableIterator<T>;
    }

    interface Keyed<K, V> {
      [Symbol.iterator](): IterableIterator<[K, V]>;
    }
  }
}
/* no more monkeys */