提取打字稿 API 的一部分

时间:2021-02-24 18:21:05

标签: typescript lodash definitelytyped

我已经使用 lodash 工具构建了 lodash-cli 的子集,我想从 @types/lodash 类型中提取相应的定义。在顶层执行此操作很容易:

import type { LoDashStatic } from "lodash";

type Whitelist        = 'pick' | 'values' | 'padEnd';
type LoDashSubset     = Pick<LoDashStatic, Whitelist>;

const _: LoDashSubset = require("./lodash-subset");

但是,如果我们考虑(显式)链接,就会有更多问题,因为各种 ExpChainCollectionChainFunctionChain 等)返回类型具有不在白名单中的属性.因此,以下内容将编译得很好:

type Whitelist        = 'pick' | 'chain';
...
_.chain({ a:[1,20], b:[2,10], c:[3,0] })
    .pick("a", "b")
    .sortBy(1)       // Uh oh! Not in Whitelist but the definition is still there.
    .value();

...但是当 JS 意识到 sortBy 不存在时,我遇到了运行时失败。

我尝试了一些映射类型的变体,但没有成功,例如:

type Whitelist        = 'intersection' | 'chain';

type Restricted<T> =
    T extends {}
        ?   {
                [K in (keyof T) & Whitelist]:
                    T[K] extends (...args: infer Args) => infer U
                        ?   (...args: Args) => Restricted<U>
                        :   T[K]
            }
        :   T;

const _: Restricted<LoDashStatic> = require("./lodash-subset");

_.intersection([1,2,3], [2,3,4]);        // okay ...
_.chain([1,2,3]);                        // also okay ...
_.chain([1,2,3]).intersection([2,3,4]);  // COMPILE ERROR.  Ah, so close.

编译失败,报错:

TS2339: Property 'intersection' does not exist on type '{ chain: () => ...; }'.

请注意,这更多是关于 Typescript 是否能胜任任务的问题,而不是是否应该完成,更不用说是否应该对 Lodash 完成!

在 TS 中可以对 API 进行如此稍微深入的切片和切块吗?

0 个答案:

没有答案