Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

d.ts 中如何覆盖全局类型?

在uni-app使用ts开发中,uni-app的promise类型返回值是错误的,我将这个错误纠正后形成一个新的类型,但我却无法覆盖 declare const uni: UniApp.Uni;的类型,我应该如何覆盖全局模块定义的类型?

这个是我定义正确的uniPromiseApi返回的类型

// types/uni.d.ts 解决uni, promise返回值不正确
type Empty = null | undefined | void | never;
type IfElse<T, D> = T extends Empty ? D : T;
type Else<T, D> = T extends Empty ? never : D;
type NonNullable<T> = T extends Empty ? never : T;
type PromiseUni<T = UniApp.Uni> = {
  [P in keyof T]: (
    ...args: Parameters<T[P]>
  ) => IfElse<
    ReturnType<T[P]>,
    Else<
      Parameters<Parameters<T[P]>[0]['success']>[0],
      Promise<
        [
          Parameters<Parameters<T[P]>[0]['fail']>[0],
          Parameters<Parameters<T[P]>[0]['success']>[0]
        ]
      >
    >
  >;
};

然后无论我怎么定义,都不能覆盖 uni 的类型

// 没有效果
declare module '@dcloudio/types' {
  declare const uni: PromiseUni;
}
// 没有效果
declare module '@dcloudio/types/uni' {
  declare const uni: PromiseUni;
}
// 没有效果
declare const uni: PromiseUni;

image.png

目前只能使用 as 断言方式解决问题,有木有更好的方法?
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

类似这样,比如往vue中添加一个全局方法,

import Vue from 'vue'

// 扩展Vue原型
declare module 'vue/types/vue' {
  interface Vue {
    $url(url: string): string;
  }
}

比如给axios添加一个code、msg检验,

import { AxiosResponse } from 'axios'

// 扩展响应数据
declare module 'axios' {
  interface AxiosResponse {
    code: number;
    msg: string;
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...