typescript第三方库没有导出类型,我们该如何使用呢?续集

134 阅读1分钟

书接上文typescript第三方库没有导出类型,我们该如何使用呢?

这次我们来讨论下泛式类和泛式函数的情况要怎么处理。

泛式类

class A<T> {
    constructor(params: InterType<T>) {}
}

ConstructorParameters<typeof A>[0] // InterType<unknow>
ConstructorParameters<typeof A<string>>[0] // 语法错误

如何准确的拿到结果InterType<string>呢?

// 用继承来解决
class B extends A<string> {}

ConstructorParameters<typeof B>[0] // InterType<string>

泛式函数

interface InternalType <T> {
    a: T;
}

function foo<T>(e: T): InternalType<T> {
    return {
        a: e
    };
}

class Wrapper<T> {
  wrapped(e: T) {
    return foo<T>(e)
  }
}

type Y = ReturnType<Wrapper<number>['wrapped']>;  // InternalType<number>
type F = Parameters<Wrapper<number>['wrapped']>[0]; // number

方案的副作用会多生成一个Class,所以不算完美。但目前未找到其他可用的方案。先凑合用吧(捂脸)。