簡體   English   中英

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

[英]How to extend typings in typescript?

我有一個庫,其中包含具有以下定義的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>

另外,我還有另一個Maybe類型的庫,它擴展了Functor ,因此可以將其與上面的map函數一起使用。

我可以使用下面的定義擴展“ library1” map函數,因此當我使用“ library1”中的map函數時,它有3個重載(上面2個,下面1個)?

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

在第一個庫中,模塊結構如下(庫類型自動生成並帶有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"

接下來,在package.json ,我有"typings": "lib/index.d.ts"

一種方法是在導入它們時重命名要擴展的類型:

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

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM