简体   繁体   English

如何扩展打字稿中的打字?

[英]How to extend typings in typescript?

I have a library, which has map function with these definitions: 我有一个库,其中包含具有以下定义的map功能:

function map<T, U>(f: (x: T) => U, a: Array<T>): Array<U>
function map<T, U>(f: (x: T) => U, a: Functor<T>): Functor<U>

Also, I have another library with Maybe type, which extends Functor , so it's possible to use it with map function above. 另外,我还有另一个Maybe类型的库,它扩展了Functor ,因此可以将其与上面的map函数一起使用。

Can I extend "library1" map function with definition below, so when I use map function from "library1" it has 3 overloads(2 above and 1 below)? 我可以使用下面的定义扩展“ library1” map函数,因此当我使用“ library1”中的map函数时,它有3个重载(上面2个,下面1个)?

function map<T, U>(f: (x: T) => U, a: Maybe<T>): Maybe<U>

In 1st library, module structure is the following(library typings are generating automatically with declaration: true setting): 在第一个库中,模块结构如下(库类型自动生成并带有declaration: true设置):

// lib/types/index.d.ts
export interface Functor<T> {
    map: <T1>(fn: (a: T) => T1) => Functor<T1>;
}
export interface MapFunction {
    /**
     * Array
     */
    <T, T1>(f: (x: T) => T1, a: Array<T>): Array<T1>;
    /**
     * Functor
     */
    <T, T1>(f: (x: T) => T1, a: Functor<T>): Functor<T1>;
}
export declare const map: MapFunction;

// lib/index.d.ts
export * from "./lib/types"

Next, in package.json , I have "typings": "lib/index.d.ts" 接下来,在package.json ,我有"typings": "lib/index.d.ts"

One way to do this is to rename the types you want to extend when you import them: 一种方法是在导入它们时重命名要扩展的类型:

import { Functor, MapFunction as _MapFunction, map as _map } from './lib'
// guessing at './lib', you might have a different project structure

interface Maybe<T> extends Functor<T> {
  map<T1>(f: (x: T) => T1): Maybe<T1>;
}
interface MapFunction extends _MapFunction {
  <T, T1>(f: (x: T) => T1, a: Maybe<T>): Maybe<T1>;
}
const map: MapFunction = _map; // assuming map is implemented generically

Hope that helps. 希望能有所帮助。

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

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